Enforce flood threshold in retry and path-prep selection

Ensure MessageRetryService forces flood once the attempt reaches floodFromAttempt even if a selector returns null, and pass SendAttemptPlan.floodFromAttempt from preparePathForContactSend so zero-budget plans keep the saved path.
This commit is contained in:
zjs81 committed 2026-11-20 22:51:35 -07:00
1 parent 27cc332383
commit 723fa18b68
4 files changed
+308 -13

No files matched your search

+12 -7
View File
@@ -5466,16 +5466,21 @@ class MeshCoreConnector extends ChangeNotifier {
Future<PathSelection> preparePathForContactSend(Contact contact) async {
PathSelection? autoSelection;
final autoRotationEnabled =
_appSettingsService?.settings.autoRouteRotationEnabled == true;
if (autoRotationEnabled && contact.pathOverride == null) {
final directRetries =
_appSettingsService?.settings.directRetries ??
SendAttemptPlan.defaultDirectRetries;
final settings = _appSettingsService?.settings;
final plan = SendAttemptPlan(
directRetries:
settings?.directRetries ?? SendAttemptPlan.defaultDirectRetries,
floodRetries:
settings?.floodRetries ?? SendAttemptPlan.defaultFloodRetries,
rotateRoutes:
settings?.autoRouteRotationEnabled == true &&
contact.pathOverride == null,
);
if (plan.rotateRoutes) {
autoSelection = _selectAutoPathForAttempt(
contact.publicKeyHex,
attemptIndex: 0,
directRetries: directRetries,
directRetries: plan.floodFromAttempt ?? (1 << 30),
);
}
+9 -2
View File
@@ -330,15 +330,22 @@ class MessageRetryService extends ChangeNotifier {
return null;
}
final floodFrom = plan.floodFromAttempt;
final recentSelections = List<PathSelection>.from(
_attemptPathHistory[message.messageId] ?? const <PathSelection>[],
);
return config.selectRetryPath!(
final selection = config.selectRetryPath!(
contact.publicKeyHex,
message.retryCount,
plan.floodFromAttempt ?? (1 << 30),
floodFrom ?? (1 << 30),
recentSelections,
);
if (floodFrom != null && message.retryCount >= floodFrom) {
return selection != null && selection.useFlood
? selection
: const PathSelection(pathBytes: [], hopCount: -1, useFlood: true);
}
return selection;
}
void _recordAttemptPathHistory(String messageId, PathSelection selection) {
+169 -4
View File
@@ -1,10 +1,15 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/models/path_history.dart';
import 'package:meshcore_open/models/path_selection.dart';
import 'package:meshcore_open/review_mode/review_radio.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
@@ -22,21 +27,68 @@ Contact _directContact() {
);
}
class _ControllablePathStorage extends StorageService {
Completer<ContactPathHistory?>? loadGate;
@override
Future<ContactPathHistory?> loadPathHistory(String contactPubKeyHex) {
final gate = loadGate;
if (gate != null && !gate.isCompleted) {
return gate.future;
}
return Future<ContactPathHistory?>.value(null);
}
}
class _RecordingReviewRadio extends ReviewRadio {
final List<Uint8List> sent = [];
_RecordingReviewRadio()
: super(
scheduledMessageInterval: const Duration(hours: 1),
// Long ACK delay so retry attempts run on timeout in tests.
ackDelay: const Duration(hours: 1),
);
@override
void handle(Uint8List frame) {
sent.add(frame);
super.handle(frame);
}
}
Future<void> _waitFor(bool Function() condition, {int seconds = 8}) async {
final end = DateTime.now().add(Duration(seconds: seconds));
while (!condition()) {
if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition');
await Future<void>.delayed(const Duration(milliseconds: 25));
}
}
// NotificationService is a process-wide singleton whose reply stream can be
// listened to once, so every test shares one connector and reconnects it to a
// fresh radio.
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late MeshCoreConnector connector;
late _ControllablePathStorage storage;
late PathHistoryService history;
late MessageRetryService retries;
late AppSettingsService settings;
setUp(() async {
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
settings = AppSettingsService();
await settings.loadSettings();
connector = MeshCoreConnector();
history = PathHistoryService(StorageService());
retries = MessageRetryService();
storage = _ControllablePathStorage();
history = PathHistoryService(storage);
retries = MessageRetryService(
sentWatchdogGrace: const Duration(milliseconds: 5),
);
connector.initialize(
retryService: retries,
pathHistoryService: history,
@@ -44,12 +96,17 @@ void main() {
);
});
tearDown(() {
tearDownAll(() {
connector.dispose();
history.dispose();
retries.dispose();
});
setUp(() async {
storage.loadGate = null;
await settings.resetRoutingSettingsToDefault();
});
test('flood attempts do not wait for route history', () async {
await settings.updateSettings(
settings.settings.copyWith(
@@ -69,5 +126,113 @@ void main() {
expect(direct.useFlood, isFalse);
expect(direct.hopCount, 1);
expect(direct.pathBytes, [0x11]);
await settings.updateSettings(
settings.settings.copyWith(directRetries: 0, floodRetries: 0),
);
final zeroBudget = await connector.preparePathForContactSend(
_directContact(),
);
expect(zeroBudget.useFlood, isFalse);
expect(zeroBudget.hopCount, 1);
expect(zeroBudget.pathBytes, [0x11]);
});
test(
'sendMessage with directRetries 0 and floodRetries 1 floods even when route history is loading',
() async {
final gate = Completer<ContactPathHistory?>();
storage.loadGate = gate;
final radio = _RecordingReviewRadio();
connector.reviewRadioFactoryForTest = () => radio;
await connector.connectReview();
addTearDown(connector.disconnect);
await _waitFor(() => connector.contacts.isNotEmpty);
final directContact = connector.contacts.firstWhere(
(c) => c.pathLength > 0,
);
await settings.updateSettings(
settings.settings.copyWith(
autoRouteRotationEnabled: true,
directRetries: 0,
floodRetries: 1,
),
);
radio.sent.clear();
await connector.sendMessage(directContact, 'flood only');
await _waitFor(
() => radio.sent.any((frame) => frame[0] == cmdSendTxtMsg),
);
final opCodes = radio.sent
.map((frame) => frame[0])
.where(
(code) =>
code == cmdResetPath ||
code == cmdAddUpdateContact ||
code == cmdSendTxtMsg,
)
.toList();
expect(opCodes, [cmdResetPath, cmdSendTxtMsg]);
gate.complete(null);
storage.loadGate = null;
},
);
test(
'sendMessage with directRetries > 0 rotates through cached paths before flooding',
() async {
final radio = _RecordingReviewRadio();
connector.reviewRadioFactoryForTest = () => radio;
await connector.connectReview();
addTearDown(connector.disconnect);
await _waitFor(() => connector.contacts.isNotEmpty);
final directContact = connector.contacts.firstWhere(
(c) => c.pathLength > 0,
);
history.recordPathResult(
directContact.publicKeyHex,
const PathSelection(pathBytes: [0x22], hopCount: 1, useFlood: false),
success: true,
);
await pumpEventQueue();
history.recordPathResult(
directContact.publicKeyHex,
const PathSelection(pathBytes: [0x33], hopCount: 1, useFlood: false),
success: true,
);
await pumpEventQueue();
await settings.updateSettings(
settings.settings.copyWith(
autoRouteRotationEnabled: true,
directRetries: 2,
floodRetries: 1,
),
);
radio.sent.clear();
await connector.sendMessage(directContact, 'rotate then flood');
await _waitFor(
() =>
radio.sent.where((frame) => frame[0] == cmdSendTxtMsg).length == 3,
seconds: 25,
);
final pathOps = radio.sent
.where(
(frame) =>
frame[0] == cmdResetPath || frame[0] == cmdAddUpdateContact,
)
.map((frame) => frame[0])
.toList();
expect(pathOps, [cmdAddUpdateContact, cmdAddUpdateContact, cmdResetPath]);
},
timeout: const Timeout(Duration(seconds: 45)),
);
}
@@ -165,4 +165,122 @@ void main() {
expect(sends, [0]);
expect(latest.last.status, MessageStatus.failed);
});
test(
'flood-only rotation floods saved direct contact even if selector returns null',
() async {
final settings = AppSettingsService();
await settings.loadSettings();
await settings.updateSettings(
settings.settings.copyWith(
autoRouteRotationEnabled: true,
directRetries: 0,
floodRetries: 1,
),
);
final service = MessageRetryService(
sentWatchdogGrace: const Duration(milliseconds: 5),
);
addTearDown(service.dispose);
final latest = <Message>[];
final sends = <int>[];
var clearedCount = 0;
var setPathCount = 0;
service.initialize(
RetryServiceConfig(
sendMessage: (_, _, attempt, _) async {
sends.add(attempt);
},
addMessage: (_, message) => latest.add(message),
updateMessage: (message) => latest.add(message),
clearContactPath: (_) async {
clearedCount++;
},
setContactPath: (_, _, _) async {
setPathCount++;
},
calculateTimeout:
(_, _, {String? contactKey, int? deviceTimeoutMs}) => 15,
appSettingsService: settings,
selectRetryPath: (_, _, _, _) => null,
),
);
await service.sendMessageWithRetry(
contact: _contact(pathLength: 1, path: const [0x11]),
text: 'hello',
);
await pumpEventQueue();
await Future<void>.delayed(const Duration(milliseconds: 200));
expect(sends, [0]);
expect(clearedCount, 1);
expect(setPathCount, 0);
expect(latest.last.pathLength, -1);
expect(latest.last.pathBytes, isEmpty);
expect(latest.last.status, MessageStatus.failed);
},
);
test(
'rotation with direct attempts > 0 tries direct paths before flooding',
() async {
final settings = AppSettingsService();
await settings.loadSettings();
await settings.updateSettings(
settings.settings.copyWith(
autoRouteRotationEnabled: true,
directRetries: 2,
floodRetries: 1,
),
);
final service = MessageRetryService(
sentWatchdogGrace: const Duration(milliseconds: 5),
);
addTearDown(service.dispose);
final actions = <String>[];
final sends = <int>[];
service.initialize(
RetryServiceConfig(
sendMessage: (_, _, attempt, _) async {
sends.add(attempt);
},
addMessage: (_, _) {},
updateMessage: (_) {},
clearContactPath: (_) async => actions.add('flood'),
setContactPath: (_, bytes, _) async =>
actions.add('direct:${bytes.join(',')}'),
calculateTimeout:
(_, _, {String? contactKey, int? deviceTimeoutMs}) => 15,
appSettingsService: settings,
selectRetryPath: (_, attemptIndex, directRetries, _) {
if (attemptIndex >= directRetries) return null;
return attemptIndex == 0
? const PathSelection(
pathBytes: [0x22],
hopCount: 1,
useFlood: false,
)
: const PathSelection(
pathBytes: [0x33],
hopCount: 1,
useFlood: false,
);
},
),
);
await service.sendMessageWithRetry(
contact: _contact(pathLength: 1, path: const [0x11]),
text: 'hello',
);
await pumpEventQueue();
await Future<void>.delayed(const Duration(milliseconds: 3500));
expect(sends, [0, 1, 2]);
expect(actions, ['direct:34', 'direct:51', 'flood']);
},
);
}