Refactor LoRa airtime tests and add new functionality
- Updated LoRa airtime calculations in `lora_airtime_test.dart` to reflect new reference values. - Introduced new tests for LDRO behavior and preamble symbol calculations. - Added `contact_path_width_test.dart` to validate path hash width handling in contacts. - Enhanced `model_changes_test.dart` to ensure legacy data migration works correctly. - Created `remote_node_stats_test.dart` to decode and validate remote node statistics. - Implemented `map_marker_parse_test.dart` for parsing marker text with coordinate validation. - Developed `map_tile_cache_key_test.dart` to ensure API keys are excluded from cache keys. - Added `message_retry_failure_test.dart` to test message retry service behavior on failures. - Extended `path_history_service_test.dart` to preserve learned state across path attempts. - Enhanced `received_image_store_test.dart` to handle concurrent writes and review fixes. - Implemented `repeater_command_service_test.dart` to validate command response handling. - Created `store_tolerant_parsing_test.dart` to ensure stores skip malformed records gracefully. - Cleared untranslated JSON file for localization updates.
This commit is contained in:
1 parent
d5f54dfa11
commit
d74587c167
105 files changed
+6419
-2072
No files matched your search
@@ -630,6 +630,9 @@ enum ImageReassemblyFailureReason {
|
||||
/// Reassembled but the metadata byte was undecodable
|
||||
/// ([ImageChunkStatus.unsupportedFormat]).
|
||||
unsupportedFormat,
|
||||
|
||||
/// Dropped by [ImageReassembler.clear] (disconnect / new session).
|
||||
disconnected,
|
||||
}
|
||||
|
||||
/// A fully reassembled image.
|
||||
@@ -852,10 +855,27 @@ class ImageReassembler {
|
||||
/// Keys of the remembered completed images (test/debug aid).
|
||||
Iterable<ImageStreamKey> get completedKeys => _recentlyCompleted.keys;
|
||||
|
||||
/// Drops everything (e.g. on disconnect). Does not fire [onFailed].
|
||||
void clear() {
|
||||
/// Drops everything (e.g. on disconnect). In-progress streams are reported
|
||||
/// through [onFailed] right away, so their bubbles stop showing "receiving";
|
||||
/// nothing is left behind for [evictExpired] to report later.
|
||||
void clear({DateTime? now}) {
|
||||
final at = now ?? _clock();
|
||||
final dropped = _pending.values.toList();
|
||||
_pending.clear();
|
||||
_recentlyCompleted.clear();
|
||||
for (final entry in dropped) {
|
||||
onFailed?.call(
|
||||
ImageReassemblyFailure(
|
||||
key: entry.key,
|
||||
total: entry.total,
|
||||
receivedDataChunks: entry.bodies.length,
|
||||
hadParity: entry.hasParity,
|
||||
firstSeen: entry.firstSeen,
|
||||
expiredAt: at,
|
||||
reason: ImageReassemblyFailureReason.disconnected,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds one received GRP_DATA blob.
|
||||
@@ -883,6 +903,12 @@ class ImageReassembler {
|
||||
// A parity chunk must carry at least its length byte.
|
||||
return ImageChunkOutcome(ImageChunkStatus.malformed, header: header);
|
||||
}
|
||||
if (!header.isParity && body.length > kImageChunkBodyBytes) {
|
||||
// The blob cap leaves room for one byte more than the XOR buffer holds;
|
||||
// such a body can never come from [buildImageChunks] and would overrun
|
||||
// parity recovery.
|
||||
return ImageChunkOutcome(ImageChunkStatus.malformed, header: header);
|
||||
}
|
||||
|
||||
final key = ImageStreamKey(
|
||||
senderPrefix: header.senderPrefix,
|
||||
|
||||
@@ -90,6 +90,10 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
|
||||
String? _lastError;
|
||||
Future<void> _queue = Future<void>.value();
|
||||
ImageCodecSession? _session;
|
||||
|
||||
/// Teardown started by [handleMemoryPressure]; [_ensureSession] waits for it
|
||||
/// so a second isolate is never spawned while the first is still resident.
|
||||
Future<void>? _pendingRelease;
|
||||
ImageCodecBundle? _loadedBundle;
|
||||
ImageCodecBundle? _failedBundle;
|
||||
int _downloadedBytes = 0;
|
||||
@@ -1339,6 +1343,12 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
|
||||
// ---- model memory (mirrors translation_service.dart:586-629) -------------
|
||||
|
||||
Future<ImageCodecSession?> _ensureSession(ImageCodecBundle bundle) async {
|
||||
final pendingRelease = _pendingRelease;
|
||||
if (pendingRelease != null) {
|
||||
try {
|
||||
await pendingRelease;
|
||||
} catch (_) {}
|
||||
}
|
||||
if (_session != null && _loadedBundle == bundle) {
|
||||
return _session;
|
||||
}
|
||||
@@ -1455,8 +1465,16 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
|
||||
if (session != null) {
|
||||
// Ask for the big half back before the shutdown handshake, so the peak
|
||||
// does not have to wait on isolate teardown.
|
||||
await session.release(decoder: true);
|
||||
await session.dispose();
|
||||
final release = () async {
|
||||
await session.release(decoder: true);
|
||||
await session.dispose();
|
||||
}();
|
||||
_pendingRelease = release;
|
||||
try {
|
||||
await release;
|
||||
} finally {
|
||||
if (identical(_pendingRelease, release)) _pendingRelease = null;
|
||||
}
|
||||
}
|
||||
appLogger.info('Image codec model evicted', tag: 'ImageCodec');
|
||||
_notify();
|
||||
|
||||
@@ -358,6 +358,19 @@ class MapTileCacheService extends ChangeNotifier {
|
||||
|
||||
String get urlTemplate => _buildUrlTemplate(appSettingsService.settings);
|
||||
|
||||
/// Cache key for a tile URL: the URL without its `api_key`, so rotating the
|
||||
/// Stadia key does not orphan every offline tile.
|
||||
static String tileCacheKey(String url) {
|
||||
final uri = Uri.tryParse(url);
|
||||
if (uri == null || !uri.queryParameters.containsKey('api_key')) return url;
|
||||
final params = Map<String, String>.of(uri.queryParameters)
|
||||
..remove('api_key');
|
||||
final stripped = params.isEmpty
|
||||
? uri.replace(query: '')
|
||||
: uri.replace(queryParameters: params);
|
||||
return stripped.toString().replaceFirst(RegExp(r'\?$'), '');
|
||||
}
|
||||
|
||||
TileBuilder? get tileBuilder => null;
|
||||
|
||||
static bool shouldApplyDarkFilterForSettings(
|
||||
@@ -614,7 +627,7 @@ class MapTileCacheService extends ChangeNotifier {
|
||||
final pending = <Future<void>>[];
|
||||
Future<void> queueDownload(String url) async {
|
||||
final future = cacheManager
|
||||
.downloadFile(url, key: url, authHeaders: authHeaders)
|
||||
.downloadFile(url, key: tileCacheKey(url), authHeaders: authHeaders)
|
||||
.then((_) {
|
||||
completed += 1;
|
||||
})
|
||||
@@ -828,6 +841,7 @@ class CachedNetworkTileProvider extends TileProvider {
|
||||
final url = getTileUrl(coordinates, options);
|
||||
return CachedNetworkImageProvider(
|
||||
url,
|
||||
cacheKey: MapTileCacheService.tileCacheKey(url),
|
||||
cacheManager: cacheManager,
|
||||
headers: headers,
|
||||
);
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'dart:convert';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import '../connector/meshcore_protocol.dart';
|
||||
import '../models/contact.dart';
|
||||
import '../models/message.dart';
|
||||
import '../models/path_selection.dart';
|
||||
@@ -34,7 +35,7 @@ typedef AckHashMapping = ({
|
||||
});
|
||||
|
||||
class RetryServiceConfig {
|
||||
final void Function(Contact, String, int, int) sendMessage;
|
||||
final FutureOr<void> Function(Contact, String, int, int) sendMessage;
|
||||
final void Function(String, Message) addMessage;
|
||||
final void Function(Message) updateMessage;
|
||||
final Function(Contact)? clearContactPath;
|
||||
@@ -209,21 +210,46 @@ class MessageRetryService extends ChangeNotifier {
|
||||
final messageId = queue.removeAt(0);
|
||||
if (_pendingMessages.containsKey(messageId)) {
|
||||
_activeMessages.add(messageId);
|
||||
_attemptSend(messageId).catchError((e) {
|
||||
debugPrint('_attemptSend threw for $messageId: $e');
|
||||
final msg = _pendingMessages[messageId];
|
||||
if (msg != null) {
|
||||
final failed = msg.copyWith(status: MessageStatus.failed);
|
||||
_pendingMessages[messageId] = failed;
|
||||
_config?.updateMessage(failed);
|
||||
}
|
||||
_onMessageResolved(messageId, contactKey);
|
||||
});
|
||||
_attemptSendOrFail(messageId);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _attemptSendOrFail(String messageId) {
|
||||
_attemptSend(messageId).catchError((Object e) {
|
||||
debugPrint('_attemptSend threw for $messageId: $e');
|
||||
_config?.debugLogService?.warn(
|
||||
'Send failed for message $messageId: $e',
|
||||
tag: 'AckHash',
|
||||
);
|
||||
_failMessage(messageId);
|
||||
});
|
||||
}
|
||||
|
||||
/// Marks a message that could not be handed to the radio as failed and
|
||||
/// releases its in-flight slot so the contact's queue keeps moving.
|
||||
void _failMessage(String messageId) {
|
||||
final message = _pendingMessages[messageId];
|
||||
if (message == null) return;
|
||||
_timeoutTimers[messageId]?.cancel();
|
||||
if (message.status != MessageStatus.failed &&
|
||||
message.status != MessageStatus.delivered) {
|
||||
_config?.updateMessage(message.copyWith(status: MessageStatus.failed));
|
||||
}
|
||||
_cleanupMessage(messageId);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Fails every pending and queued message. Call when the radio link drops:
|
||||
/// nothing in flight can be sent or acknowledged any more.
|
||||
void failAllPending() {
|
||||
_sendQueue.clear();
|
||||
for (final messageId in _pendingMessages.keys.toList()) {
|
||||
_failMessage(messageId);
|
||||
}
|
||||
}
|
||||
|
||||
void _onMessageResolved(String messageId, String contactKey) {
|
||||
if (_resolvedMessages.contains(messageId)) return;
|
||||
_resolvedMessages.add(messageId);
|
||||
@@ -358,6 +384,9 @@ class MessageRetryService extends ChangeNotifier {
|
||||
// Compute expected ACK hash that device will return in RESP_CODE_SENT
|
||||
// IMPORTANT: Use the transformed text (with SMAZ encoding if enabled) to match device's hash
|
||||
final selfPubKey = config.getSelfPublicKey?.call();
|
||||
if (config.getSelfPublicKey != null && selfPubKey == null) {
|
||||
throw StateError('Self public key unknown; cannot track ACK');
|
||||
}
|
||||
if (selfPubKey != null) {
|
||||
final outboundText =
|
||||
config.prepareContactOutboundText?.call(contact, message.text) ??
|
||||
@@ -380,7 +409,7 @@ class MessageRetryService extends ChangeNotifier {
|
||||
);
|
||||
}
|
||||
|
||||
config.sendMessage(contact, message.text, attempt, timestampSeconds);
|
||||
await config.sendMessage(contact, message.text, attempt, timestampSeconds);
|
||||
}
|
||||
|
||||
bool updateMessageFromSent(int ackHash, int timeoutMs) {
|
||||
@@ -535,7 +564,8 @@ class MessageRetryService extends ChangeNotifier {
|
||||
tag: 'AckHash',
|
||||
);
|
||||
|
||||
if (message.retryCount < maxRetries - 1) {
|
||||
if (message.retryCount < maxRetries - 1 &&
|
||||
_textFitsAttempt(message, contact, message.retryCount + 1)) {
|
||||
final backoffMs = 1000 * (1 << message.retryCount);
|
||||
|
||||
if (selection != null) {
|
||||
@@ -563,7 +593,7 @@ class MessageRetryService extends ChangeNotifier {
|
||||
|
||||
_timeoutTimers[messageId] = Timer(Duration(milliseconds: backoffMs), () {
|
||||
if (_pendingMessages.containsKey(messageId)) {
|
||||
_attemptSend(messageId);
|
||||
_attemptSendOrFail(messageId);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
@@ -598,6 +628,17 @@ class MessageRetryService extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
/// From attempt 4 on the firmware appends [0][attempt] to the payload and
|
||||
/// rejects text longer than MAX_TEXT_LEN - 2 (BaseChatMesh::composeMsgPacket).
|
||||
bool _textFitsAttempt(Message message, Contact contact, int attempt) {
|
||||
if (attempt <= maxFullLengthTextAttempt) return true;
|
||||
final outboundText =
|
||||
_config?.prepareContactOutboundText?.call(contact, message.text) ??
|
||||
message.text;
|
||||
return utf8.encode(outboundText).length <=
|
||||
maxTextPayloadBytesAfterFullLengthAttempts;
|
||||
}
|
||||
|
||||
void _moveAckHashesToHistory(String messageId) {
|
||||
final ackHashes = _expectedAckHashes.remove(messageId);
|
||||
if (ackHashes != null && ackHashes.isNotEmpty) {
|
||||
|
||||
@@ -9,8 +9,7 @@ class PathHistoryService extends ChangeNotifier {
|
||||
final Map<String, ContactPathHistory> _cache = {};
|
||||
final Map<String, int> _autoRotationIndex = {};
|
||||
final Map<String, _FloodStats> _floodStats = {};
|
||||
final Set<String> _pendingLoads = {};
|
||||
final Map<String, List<_DeferredPathRecord>> _deferredRecords = {};
|
||||
final Map<String, Future<void>> _pendingLoads = {};
|
||||
|
||||
// LRU cache eviction tracking
|
||||
static const int _maxCachedContacts = 50;
|
||||
@@ -23,6 +22,16 @@ class PathHistoryService extends ChangeNotifier {
|
||||
|
||||
PathHistoryService(this._storage);
|
||||
|
||||
void setDevicePublicKey(String publicKeyHex) {
|
||||
_storage.setPublicKeyHex = publicKeyHex;
|
||||
_cache.clear();
|
||||
_cacheAccessOrder.clear();
|
||||
_autoRotationIndex.clear();
|
||||
_floodStats.clear();
|
||||
_version++;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> initialize() async {
|
||||
// Load cached path histories on startup if needed
|
||||
}
|
||||
@@ -40,7 +49,7 @@ class PathHistoryService extends ChangeNotifier {
|
||||
pathBytes: contact.path,
|
||||
successCount: 0,
|
||||
failureCount: 0,
|
||||
routeWeight: initialWeight,
|
||||
initialWeight: initialWeight,
|
||||
timestamp: null,
|
||||
);
|
||||
}
|
||||
@@ -74,6 +83,20 @@ class PathHistoryService extends ChangeNotifier {
|
||||
double maxWeight = 5.0,
|
||||
}) {
|
||||
if (pathBytes.isEmpty || hopCount < 0) return;
|
||||
if (!_cache.containsKey(contactPubKeyHex)) {
|
||||
_ensureLoaded(contactPubKeyHex).then((_) {
|
||||
if (!_cache.containsKey(contactPubKeyHex)) return;
|
||||
recordFloodPathAttribution(
|
||||
contactPubKeyHex: contactPubKeyHex,
|
||||
pathBytes: pathBytes,
|
||||
hopCount: hopCount,
|
||||
tripTimeMs: tripTimeMs,
|
||||
successIncrement: successIncrement,
|
||||
maxWeight: maxWeight,
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
final existing = _findPathRecord(contactPubKeyHex, pathBytes);
|
||||
final successCount = (existing?.successCount ?? 0) + 1;
|
||||
@@ -124,6 +147,22 @@ class PathHistoryService extends ChangeNotifier {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_cache.containsKey(contactPubKeyHex)) {
|
||||
_ensureLoaded(contactPubKeyHex).then((_) {
|
||||
if (!_cache.containsKey(contactPubKeyHex)) return;
|
||||
recordPathResult(
|
||||
contactPubKeyHex,
|
||||
selection,
|
||||
success: success,
|
||||
tripTimeMs: tripTimeMs,
|
||||
successIncrement: successIncrement,
|
||||
failureDecrement: failureDecrement,
|
||||
maxWeight: maxWeight,
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
final existing = _findPathRecord(contactPubKeyHex, selection.pathBytes);
|
||||
final successCount = (existing?.successCount ?? 0) + (success ? 1 : 0);
|
||||
final failureCount = (existing?.failureCount ?? 0) + (success ? 0 : 1);
|
||||
@@ -222,73 +261,11 @@ class PathHistoryService extends ChangeNotifier {
|
||||
required List<int> pathBytes,
|
||||
required int successCount,
|
||||
required int failureCount,
|
||||
double routeWeight = 1.0,
|
||||
double? routeWeight,
|
||||
double initialWeight = 1.0,
|
||||
DateTime? timestamp,
|
||||
}) {
|
||||
var history = _cache[contactPubKeyHex];
|
||||
|
||||
if (history == null) {
|
||||
// If a load is already in progress, defer this record
|
||||
if (_pendingLoads.contains(contactPubKeyHex)) {
|
||||
_deferredRecords.putIfAbsent(contactPubKeyHex, () => []);
|
||||
_deferredRecords[contactPubKeyHex]!.add(
|
||||
_DeferredPathRecord(
|
||||
hopCount: hopCount,
|
||||
tripTimeMs: tripTimeMs,
|
||||
wasFloodDiscovery: wasFloodDiscovery,
|
||||
pathBytes: pathBytes,
|
||||
successCount: successCount,
|
||||
failureCount: failureCount,
|
||||
routeWeight: routeWeight,
|
||||
timestamp: timestamp,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
_pendingLoads.add(contactPubKeyHex);
|
||||
_loadHistoryFromStorage(contactPubKeyHex).then((loaded) {
|
||||
_cache[contactPubKeyHex] =
|
||||
loaded ??
|
||||
ContactPathHistory(
|
||||
contactPubKeyHex: contactPubKeyHex,
|
||||
recentPaths: [],
|
||||
);
|
||||
_addPathRecordInternal(
|
||||
contactPubKeyHex,
|
||||
hopCount,
|
||||
tripTimeMs,
|
||||
wasFloodDiscovery,
|
||||
pathBytes,
|
||||
successCount,
|
||||
failureCount,
|
||||
routeWeight,
|
||||
timestamp,
|
||||
);
|
||||
|
||||
// Apply any deferred records
|
||||
final deferred = _deferredRecords.remove(contactPubKeyHex);
|
||||
if (deferred != null) {
|
||||
for (final record in deferred) {
|
||||
_addPathRecordInternal(
|
||||
contactPubKeyHex,
|
||||
record.hopCount,
|
||||
record.tripTimeMs,
|
||||
record.wasFloodDiscovery,
|
||||
record.pathBytes,
|
||||
record.successCount,
|
||||
record.failureCount,
|
||||
record.routeWeight,
|
||||
record.timestamp,
|
||||
);
|
||||
}
|
||||
}
|
||||
_pendingLoads.remove(contactPubKeyHex);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
_addPathRecordInternal(
|
||||
void add() => _addPathRecordInternal(
|
||||
contactPubKeyHex,
|
||||
hopCount,
|
||||
tripTimeMs,
|
||||
@@ -297,8 +274,34 @@ class PathHistoryService extends ChangeNotifier {
|
||||
successCount,
|
||||
failureCount,
|
||||
routeWeight,
|
||||
initialWeight,
|
||||
timestamp,
|
||||
);
|
||||
|
||||
if (_cache.containsKey(contactPubKeyHex)) {
|
||||
add();
|
||||
} else {
|
||||
_ensureLoaded(contactPubKeyHex).then((_) => 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);
|
||||
});
|
||||
}
|
||||
|
||||
void _addPathRecordInternal(
|
||||
@@ -309,7 +312,8 @@ class PathHistoryService extends ChangeNotifier {
|
||||
List<int> pathBytes,
|
||||
int successCount,
|
||||
int failureCount,
|
||||
double routeWeight,
|
||||
double? routeWeight,
|
||||
double initialWeight,
|
||||
DateTime? timestamp,
|
||||
) {
|
||||
var history = _cache[contactPubKeyHex];
|
||||
@@ -326,6 +330,7 @@ class PathHistoryService extends ChangeNotifier {
|
||||
wasFloodDiscovery = existing.wasFloodDiscovery || wasFloodDiscovery;
|
||||
timestamp ??= existing.timestamp;
|
||||
}
|
||||
routeWeight ??= existing?.routeWeight ?? initialWeight;
|
||||
|
||||
final newRecord = PathRecord(
|
||||
hopCount: hopCount,
|
||||
@@ -368,11 +373,8 @@ class PathHistoryService extends ChangeNotifier {
|
||||
return history.recentPaths;
|
||||
}
|
||||
|
||||
_loadHistoryFromStorage(contactPubKeyHex).then((loaded) {
|
||||
if (loaded != null) {
|
||||
_cache[contactPubKeyHex] = loaded;
|
||||
_trackAccess(contactPubKeyHex);
|
||||
_evictIfNeeded();
|
||||
_ensureLoaded(contactPubKeyHex).then((_) {
|
||||
if (_cache[contactPubKeyHex]?.recentPaths.isNotEmpty ?? false) {
|
||||
_version++;
|
||||
notifyListeners();
|
||||
}
|
||||
@@ -579,28 +581,6 @@ class PathHistoryService extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
class _DeferredPathRecord {
|
||||
final int hopCount;
|
||||
final int tripTimeMs;
|
||||
final bool wasFloodDiscovery;
|
||||
final List<int> pathBytes;
|
||||
final int successCount;
|
||||
final int failureCount;
|
||||
final double routeWeight;
|
||||
final DateTime? timestamp;
|
||||
|
||||
_DeferredPathRecord({
|
||||
required this.hopCount,
|
||||
required this.tripTimeMs,
|
||||
required this.wasFloodDiscovery,
|
||||
required this.pathBytes,
|
||||
required this.successCount,
|
||||
required this.failureCount,
|
||||
this.routeWeight = 1.0,
|
||||
this.timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
class _FloodStats {
|
||||
int successCount = 0;
|
||||
int failureCount = 0;
|
||||
|
||||
@@ -66,6 +66,10 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
String? _dirPath;
|
||||
Future<String>? _pending;
|
||||
|
||||
/// Last queued sidecar operation per id. Writes share one `.tmp` path, so
|
||||
/// two in flight for the same id would interleave; each waits for the last.
|
||||
final Map<String, Future<void>> _sidecarOps = <String, Future<void>>{};
|
||||
|
||||
FileReceivedImageBlobStore({
|
||||
Future<Directory> Function()? baseDirectory,
|
||||
this.directoryName = 'received_images',
|
||||
@@ -190,7 +194,19 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
/// atomic within a directory on every platform we ship, so a reader either
|
||||
/// sees the old record or the new one.
|
||||
@override
|
||||
Future<void> writeSidecar(String streamId, String json) async {
|
||||
Future<void> writeSidecar(String streamId, String json) =>
|
||||
_serializeSidecar(streamId, () => _writeSidecarNow(streamId, json));
|
||||
|
||||
Future<void> _serializeSidecar(String streamId, Future<void> Function() op) {
|
||||
final previous = _sidecarOps[streamId] ?? Future<void>.value();
|
||||
final next = previous.then((_) => op());
|
||||
_sidecarOps[streamId] = next;
|
||||
return next.whenComplete(() {
|
||||
if (identical(_sidecarOps[streamId], next)) _sidecarOps.remove(streamId);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _writeSidecarNow(String streamId, String json) async {
|
||||
try {
|
||||
final finalPath = await _pathFor(streamId, _sidecarExt);
|
||||
final tmpPath = await _pathFor(streamId, _tmpExt);
|
||||
@@ -207,10 +223,11 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> deleteSidecar(String streamId) async {
|
||||
await _delete(streamId, _sidecarExt);
|
||||
await _delete(streamId, _tmpExt);
|
||||
}
|
||||
Future<void> deleteSidecar(String streamId) =>
|
||||
_serializeSidecar(streamId, () async {
|
||||
await _delete(streamId, _sidecarExt);
|
||||
await _delete(streamId, _tmpExt);
|
||||
});
|
||||
|
||||
/// Startup scan. Also the only place orphaned bytes are reaped: anything
|
||||
/// whose sidecar is gone is invisible to the store and therefore to the
|
||||
|
||||
@@ -595,6 +595,10 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
/// True when the queue stopped because the codec was busy encoding. Cleared
|
||||
/// by anything that could plausibly have freed it.
|
||||
bool _parkedOnBusyDecoder = false;
|
||||
|
||||
/// Set by [handleMemoryPressure] so the decode it cancels is parked rather
|
||||
/// than reported as corrupt.
|
||||
bool _cancelRequested = false;
|
||||
bool _foreground = true;
|
||||
bool _disposed = false;
|
||||
|
||||
@@ -775,10 +779,13 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
// `conflicting` means the reassembler threw the old stream away and
|
||||
// restarted from this chunk. A stream that had already been surfaced
|
||||
// keeps its id (and therefore its message) only if it was still
|
||||
// receiving; anything else gets a fresh entry.
|
||||
// receiving; anything else gets a fresh entry. The same goes for a
|
||||
// plain `accepted`: once an entry is past `receiving` the reassembler
|
||||
// reports its stragglers as `duplicate`, so an accepted chunk on that
|
||||
// key is a new image reusing the 8-bit id and must not overwrite it.
|
||||
final resets = outcome.status == ImageChunkStatus.conflicting;
|
||||
if (existing != null &&
|
||||
(!resets || existing.state == ReceivedImageState.receiving)) {
|
||||
existing.state == ReceivedImageState.receiving) {
|
||||
final updated = existing.copyWith(
|
||||
state: ReceivedImageState.receiving,
|
||||
receivedChunks: resets
|
||||
@@ -824,7 +831,9 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
channelIndex: channelIndex,
|
||||
),
|
||||
);
|
||||
if (entry == null) return null;
|
||||
if (entry == null || entry.state != ReceivedImageState.receiving) {
|
||||
return null;
|
||||
}
|
||||
_queue.remove(entry.streamId);
|
||||
return _store(
|
||||
entry.copyWith(
|
||||
@@ -847,7 +856,9 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
) async {
|
||||
final key = result.key;
|
||||
var entry = entryForKey(key);
|
||||
if (entry == null) {
|
||||
// A one-chunk image completes without an `accepted` first, so the key may
|
||||
// still point at an older, finished image that reused the id.
|
||||
if (entry == null || entry.state != ReceivedImageState.receiving) {
|
||||
final streamId = _uniqueStreamId(
|
||||
senderPrefix: key.senderPrefix,
|
||||
imgId: key.imgId,
|
||||
@@ -906,7 +917,7 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
// Already completed by a later chunk; the failure is stale.
|
||||
return entry;
|
||||
}
|
||||
return _store(
|
||||
final failed = await _store(
|
||||
entry.copyWith(
|
||||
// `isCorrupt` means every chunk arrived but the bytes were unusable
|
||||
// (CRC-16 mismatch or an undecodable metadata byte). The UI must say
|
||||
@@ -919,6 +930,8 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
error: failure.isCorrupt ? failure.reason.name : null,
|
||||
),
|
||||
);
|
||||
await evictToBudget(protect: failed.streamId);
|
||||
return failed;
|
||||
}
|
||||
|
||||
/// Records the local user's own send so the outgoing bubble can show the real
|
||||
@@ -1027,6 +1040,7 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
/// Cancels the running decode and stops the queue; the entry goes back to
|
||||
/// `reassembled` and will be picked up again later.
|
||||
Future<void> handleMemoryPressure() async {
|
||||
_cancelRequested = true;
|
||||
decoder?.cancelCodecJob();
|
||||
_queue.clear();
|
||||
for (final entry in _entries.values.toList()) {
|
||||
@@ -1190,6 +1204,7 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
return;
|
||||
}
|
||||
final started = _clock();
|
||||
_cancelRequested = false;
|
||||
await _store(entry.copyWith(state: ReceivedImageState.decoding));
|
||||
|
||||
ImageCodecResult? result;
|
||||
@@ -1201,7 +1216,14 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
);
|
||||
} catch (error) {
|
||||
final current = _entries[entry.streamId] ?? entry;
|
||||
if (!_foreground) {
|
||||
if (_cancelRequested) {
|
||||
await _store(
|
||||
current.copyWith(
|
||||
state: ReceivedImageState.reassembled,
|
||||
needsManualDecode: true,
|
||||
),
|
||||
);
|
||||
} else if (!_foreground) {
|
||||
await _store(current.copyWith(state: ReceivedImageState.reassembled));
|
||||
} else {
|
||||
await _store(
|
||||
@@ -1224,6 +1246,16 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
}
|
||||
final png = result.pngBytes;
|
||||
if (result.status != ImageCodecStatus.completed || png == null) {
|
||||
if (_cancelRequested) {
|
||||
// The codec reports a killed job as `failed`; the bitstream is fine.
|
||||
await _store(
|
||||
current.copyWith(
|
||||
state: ReceivedImageState.reassembled,
|
||||
needsManualDecode: true,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
await _store(
|
||||
current.copyWith(
|
||||
state: ReceivedImageState.failedCorrupt,
|
||||
@@ -1348,9 +1380,15 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
final evicted = <String>[];
|
||||
final now = _clock();
|
||||
|
||||
// 1. Age budget: nothing survives, not even the bitstream.
|
||||
// 1. Age budget: nothing survives, not even the bitstream. A failed image
|
||||
// has no bubble worth keeping, so it goes entirely, sidecar included.
|
||||
for (final entry in _entries.values.toList()) {
|
||||
if (now.difference(entry.firstSeen) <= maxAge) continue;
|
||||
if (entry.state.isFailure) {
|
||||
await deleteImage(entry.streamId);
|
||||
evicted.add(entry.streamId);
|
||||
continue;
|
||||
}
|
||||
if (!entry.pngStored && !entry.bitstreamStored) continue;
|
||||
await blobs.deletePng(entry.streamId);
|
||||
await blobs.deleteBitstream(entry.streamId);
|
||||
@@ -1414,6 +1452,22 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
evicted.add(victim.streamId);
|
||||
}
|
||||
|
||||
// 3. Failed entries hold no PNG, so the loop above never counts them; cap
|
||||
// them by entry count, oldest first, or a noisy mesh grows the sidecars
|
||||
// (and the startup load) without bound.
|
||||
if (_entries.length > maxImages) {
|
||||
final failures =
|
||||
_entries.values
|
||||
.where((e) => e.state.isFailure && e.streamId != protect)
|
||||
.toList()
|
||||
..sort((a, b) => a.firstSeen.compareTo(b.firstSeen));
|
||||
for (final victim in failures) {
|
||||
if (_entries.length <= maxImages) break;
|
||||
await deleteImage(victim.streamId);
|
||||
evicted.add(victim.streamId);
|
||||
}
|
||||
}
|
||||
|
||||
if (evicted.isNotEmpty) _notify();
|
||||
return evicted;
|
||||
}
|
||||
|
||||
@@ -11,9 +11,7 @@ import '../connector/meshcore_protocol.dart';
|
||||
/// do the same so the repeater always gets the phone's time.
|
||||
String normalizeRepeaterClockSyncCommand(String command, {int? nowSeconds}) {
|
||||
final epoch = nowSeconds ?? DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
||||
return command.trim().toLowerCase() == 'clock sync'
|
||||
? 'time $epoch'
|
||||
: command;
|
||||
return command.trim().toLowerCase() == 'clock sync' ? 'time $epoch' : command;
|
||||
}
|
||||
|
||||
class RepeaterCommandService {
|
||||
@@ -25,19 +23,22 @@ class RepeaterCommandService {
|
||||
int _prefixCounter = 0;
|
||||
|
||||
static const int maxRetries = 5;
|
||||
static final RegExp _prefixPattern = RegExp(r'^[0-9A-Fa-f]{2}\|');
|
||||
|
||||
RepeaterCommandService(this._connector);
|
||||
|
||||
/// Send a CLI command to a repeater with automatic retries
|
||||
/// Returns a future that completes when a response is received or after max retries
|
||||
/// Returns a future that completes when a response is received or after max retries.
|
||||
/// With [raw], the command is sent verbatim without the `XX|` reply prefix.
|
||||
Future<String> sendCommand(
|
||||
Contact repeater,
|
||||
String command, {
|
||||
Function(String)? onResponse,
|
||||
Function(int)? onAttempt,
|
||||
int retries = maxRetries,
|
||||
bool raw = false,
|
||||
}) async {
|
||||
command = normalizeRepeaterClockSyncCommand(command);
|
||||
if (!raw) command = normalizeRepeaterClockSyncCommand(command);
|
||||
final attemptCount = retries < 1 ? 1 : retries;
|
||||
final selection = await _connector.preparePathForContactSend(repeater);
|
||||
|
||||
@@ -49,6 +50,7 @@ class RepeaterCommandService {
|
||||
command,
|
||||
selection,
|
||||
attempt,
|
||||
raw,
|
||||
);
|
||||
onResponse?.call(response);
|
||||
return response;
|
||||
@@ -65,6 +67,7 @@ class RepeaterCommandService {
|
||||
String command,
|
||||
PathSelection selection,
|
||||
int attempt,
|
||||
bool raw,
|
||||
) async {
|
||||
final repeaterKey = repeater.publicKeyHex;
|
||||
final prefix = _nextPrefixToken();
|
||||
@@ -75,7 +78,7 @@ class RepeaterCommandService {
|
||||
_pendingByPrefix[prefix] = commandId;
|
||||
|
||||
try {
|
||||
final framedCommand = '$prefix$command';
|
||||
final framedCommand = raw ? command : '$prefix$command';
|
||||
final pathLengthValue = selection.useFlood ? -1 : selection.hopCount;
|
||||
final timestampSeconds = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
||||
_connector.trackRepeaterAck(
|
||||
@@ -125,6 +128,15 @@ class RepeaterCommandService {
|
||||
}
|
||||
}
|
||||
|
||||
/// Send [line] verbatim and don't wait for a reply. While `region load` is
|
||||
/// active the firmware consumes each line before prefix stripping and
|
||||
/// sends nothing back (simple_repeater/MyMesh.cpp handleCommand).
|
||||
Future<void> sendUnansweredLine(Contact repeater, String line) {
|
||||
return _connector.sendFrame(
|
||||
buildSendCliCommandFrame(repeater.publicKey, line),
|
||||
);
|
||||
}
|
||||
|
||||
/// Call this when a text message response is received from a repeater
|
||||
void handleResponse(Contact repeater, String responseText) {
|
||||
// Find pending command for this repeater and complete it
|
||||
@@ -132,14 +144,17 @@ class RepeaterCommandService {
|
||||
|
||||
String? commandId;
|
||||
String responsePayload = responseText;
|
||||
if (responseText.length >= 3 && responseText[2] == '|') {
|
||||
final prefix = responseText.substring(0, 3);
|
||||
if (_prefixPattern.hasMatch(responseText)) {
|
||||
final prefix = responseText.substring(0, 3).toUpperCase();
|
||||
commandId = _pendingByPrefix[prefix];
|
||||
if (commandId == null || !commandId.startsWith('${repeaterKey}_')) {
|
||||
return;
|
||||
}
|
||||
responsePayload = responseText.substring(3).trimLeft();
|
||||
}
|
||||
|
||||
commandId ??= _pendingCommands.keys.firstWhere(
|
||||
(id) => id.startsWith(repeaterKey),
|
||||
(id) => id.startsWith('${repeaterKey}_'),
|
||||
orElse: () => '',
|
||||
);
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'dart:convert';
|
||||
import '../models/delivery_observation.dart';
|
||||
import '../models/path_history.dart';
|
||||
import '../storage/prefs_manager.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
|
||||
class StorageService {
|
||||
static const String _pathHistoryPrefix = 'path_history_';
|
||||
@@ -11,6 +12,14 @@ class StorageService {
|
||||
'repeater_auto_clock_sync_after_login';
|
||||
static const String _deliveryObservationsKey = 'delivery_observations';
|
||||
|
||||
String _publicKeyHex = '';
|
||||
set setPublicKeyHex(String value) =>
|
||||
_publicKeyHex = value.length > 10 ? value.substring(0, 10) : '';
|
||||
|
||||
String _pathHistoryKey(String contactPubKeyHex) => _publicKeyHex.isEmpty
|
||||
? '$_pathHistoryPrefix$contactPubKeyHex'
|
||||
: '$_pathHistoryPrefix${_publicKeyHex}_$contactPubKeyHex';
|
||||
|
||||
Future<Map<String, bool>> _loadRepeaterAutoClockSyncAfterLogin() async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final jsonStr = prefs.getString(_repeaterAutoClockSyncAfterLoginKey);
|
||||
@@ -48,15 +57,18 @@ class StorageService {
|
||||
ContactPathHistory history,
|
||||
) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '$_pathHistoryPrefix$contactPubKeyHex';
|
||||
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 key = '$_pathHistoryPrefix$contactPubKeyHex';
|
||||
final jsonStr = prefs.getString(key);
|
||||
final key = _pathHistoryKey(contactPubKeyHex);
|
||||
// Fall back to the pre-scoping key so learned routes survive the upgrade.
|
||||
final jsonStr =
|
||||
prefs.getString(key) ??
|
||||
prefs.getString('$_pathHistoryPrefix$contactPubKeyHex');
|
||||
|
||||
if (jsonStr == null) return null;
|
||||
|
||||
@@ -70,8 +82,8 @@ class StorageService {
|
||||
|
||||
Future<void> clearPathHistory(String contactPubKeyHex) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = '$_pathHistoryPrefix$contactPubKeyHex';
|
||||
await prefs.remove(key);
|
||||
await prefs.remove(_pathHistoryKey(contactPubKeyHex));
|
||||
await prefs.remove('$_pathHistoryPrefix$contactPubKeyHex');
|
||||
}
|
||||
|
||||
Future<void> clearAllPathHistories() async {
|
||||
@@ -173,14 +185,24 @@ class StorageService {
|
||||
|
||||
if (jsonStr == null) return [];
|
||||
|
||||
final List<dynamic> list;
|
||||
try {
|
||||
final list = jsonDecode(jsonStr) as List;
|
||||
return list
|
||||
.map((e) => DeliveryObservation.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
list = jsonDecode(jsonStr) as List<dynamic>;
|
||||
} catch (e) {
|
||||
appLogger.warn('Stored delivery observations are unreadable: $e');
|
||||
return [];
|
||||
}
|
||||
final observations = <DeliveryObservation>[];
|
||||
for (final e in list) {
|
||||
try {
|
||||
observations.add(
|
||||
DeliveryObservation.fromJson(e as Map<String, dynamic>),
|
||||
);
|
||||
} catch (err) {
|
||||
appLogger.warn('Skipping malformed delivery observation: $err');
|
||||
}
|
||||
}
|
||||
return observations;
|
||||
}
|
||||
|
||||
Future<void> clearDeliveryObservations() async {
|
||||
|
||||
@@ -58,7 +58,10 @@ class TranslationFileStore {
|
||||
required Stream<List<int>> chunks,
|
||||
}) async {
|
||||
final directoryPath = await modelDirectoryPath();
|
||||
final file = File('$directoryPath/$fileName');
|
||||
final finalPath = '$directoryPath/$fileName';
|
||||
// Hidden until complete, so a killed download is swept by
|
||||
// [scanDownloadedModels] instead of being registered as a model.
|
||||
final file = File(_partPath(directoryPath, fileName));
|
||||
final sink = file.openWrite();
|
||||
var fileSizeBytes = 0;
|
||||
var completed = false;
|
||||
@@ -74,8 +77,9 @@ class TranslationFileStore {
|
||||
await file.delete();
|
||||
}
|
||||
}
|
||||
await file.rename(finalPath);
|
||||
return DownloadedModelFile(
|
||||
localPath: file.path,
|
||||
localPath: finalPath,
|
||||
fileSizeBytes: fileSizeBytes,
|
||||
);
|
||||
}
|
||||
@@ -91,7 +95,8 @@ class TranslationFileStore {
|
||||
}) async {
|
||||
final dir = await modelDirectoryPath();
|
||||
final finalPath = '$dir/$fileName';
|
||||
final sink = File(finalPath).openWrite();
|
||||
final partPath = _partPath(dir, fileName);
|
||||
final sink = File(partPath).openWrite();
|
||||
var totalSize = 0;
|
||||
var completed = false;
|
||||
try {
|
||||
@@ -110,14 +115,18 @@ class TranslationFileStore {
|
||||
}
|
||||
}
|
||||
if (!completed) {
|
||||
final finalFile = File(finalPath);
|
||||
if (finalFile.existsSync()) {
|
||||
await finalFile.delete();
|
||||
final partFile = File(partPath);
|
||||
if (partFile.existsSync()) {
|
||||
await partFile.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
await File(partPath).rename(finalPath);
|
||||
return DownloadedModelFile(localPath: finalPath, fileSizeBytes: totalSize);
|
||||
}
|
||||
|
||||
String _partPath(String dir, String fileName) =>
|
||||
fileName.startsWith('.') ? '$dir/$fileName.part' : '$dir/.$fileName.part';
|
||||
}
|
||||
|
||||
class DownloadedModelFile {
|
||||
|
||||
@@ -271,10 +271,19 @@ class TranslationService extends ChangeNotifier {
|
||||
_downloadTotalBytes ??= response.contentLength;
|
||||
_notify();
|
||||
final trackedStream = _trackDownloadProgress(response.stream);
|
||||
return await _fileStore.writeModelBytes(
|
||||
final downloaded = await _fileStore.writeModelBytes(
|
||||
fileName: fileName,
|
||||
chunks: trackedStream,
|
||||
);
|
||||
final expected = response.contentLength;
|
||||
if (expected != null && downloaded.fileSizeBytes != expected) {
|
||||
await _fileStore.deleteFile(downloaded.localPath);
|
||||
throw StateError(
|
||||
'Model download incomplete: '
|
||||
'${downloaded.fileSizeBytes} of $expected bytes',
|
||||
);
|
||||
}
|
||||
return downloaded;
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
@@ -350,10 +359,17 @@ class TranslationService extends ChangeNotifier {
|
||||
);
|
||||
}
|
||||
final trackedStream = _trackDownloadProgress(response.stream);
|
||||
await _fileStore.writeModelBytes(
|
||||
final downloaded = await _fileStore.writeModelBytes(
|
||||
fileName: chunkPath.split(RegExp(r'[/\\]')).last,
|
||||
chunks: trackedStream,
|
||||
);
|
||||
final expected = end - start + 1;
|
||||
if (downloaded.fileSizeBytes != expected) {
|
||||
throw StateError(
|
||||
'Range download incomplete: '
|
||||
'${downloaded.fileSizeBytes} of $expected bytes',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void cancelDownload() {
|
||||
|
||||
@@ -399,7 +399,9 @@ class UsbSerialService {
|
||||
return;
|
||||
}
|
||||
if (data is ByteData) {
|
||||
_ingestRawBytes(data.buffer.asUint8List());
|
||||
_ingestRawBytes(
|
||||
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes),
|
||||
);
|
||||
return;
|
||||
}
|
||||
_addFrameError(
|
||||
@@ -412,7 +414,11 @@ class UsbSerialService {
|
||||
}
|
||||
|
||||
void _handleSerialDone() {
|
||||
final wasConnected = _status == UsbSerialStatus.connected;
|
||||
unawaited(disconnect());
|
||||
if (wasConnected) {
|
||||
_addFrameError(StateError('USB serial connection closed'));
|
||||
}
|
||||
}
|
||||
|
||||
void _ingestRawBytes(Uint8List bytes) {
|
||||
|
||||
Reference in new issue
Block a user