commit
df478dc865
@ -0,0 +1,61 @@
|
||||
import '../models/channel.dart';
|
||||
|
||||
/// Why a channel slot could not be allocated.
|
||||
enum ChannelSlotRefusal {
|
||||
/// The channel list is mid-rewrite, so no slot can be trusted to be free.
|
||||
syncing,
|
||||
|
||||
/// Every slot on the radio is in use.
|
||||
full,
|
||||
}
|
||||
|
||||
/// Either a slot that is safe to write, or the reason it was refused.
|
||||
class ChannelSlotDecision {
|
||||
const ChannelSlotDecision.slot(int this.slot) : refusal = null;
|
||||
const ChannelSlotDecision.refused(ChannelSlotRefusal this.refusal)
|
||||
: slot = null;
|
||||
|
||||
final int? slot;
|
||||
final ChannelSlotRefusal? refusal;
|
||||
|
||||
bool get isAllowed => slot != null;
|
||||
}
|
||||
|
||||
/// Decide which channel slot a new channel may occupy (#1021).
|
||||
///
|
||||
/// Pulled out of the channels screen so it can be tested without a widget, and
|
||||
/// so the QR and config-import paths can share one answer instead of each
|
||||
/// carrying their own (there were three divergent implementations, and only one
|
||||
/// of them had the bug).
|
||||
///
|
||||
/// Two refusals, both deliberate:
|
||||
///
|
||||
/// * [isSyncing] true means the connector has emptied its channel list and is
|
||||
/// refilling it slot by slot. Any index would look free. Choosing one here is
|
||||
/// what overwrote Public: a slot picked during a sync pointed at an occupied
|
||||
/// slot by the time it was written.
|
||||
/// * No free index means the radio is full. The caller must be told, never
|
||||
/// handed slot 0 as a consolation, which is the old `return 0` bug and is
|
||||
/// where Public normally lives.
|
||||
///
|
||||
/// Callers pass the connector's `isChannelTableBusy` (a sync, or a write the
|
||||
/// radio has not answered yet), not `hasLoadedChannels`: the latter stays false
|
||||
/// after a *failed* sync while the cached list is restored into use, so gating
|
||||
/// on it would refuse forever on a flaky link.
|
||||
///
|
||||
/// An absent index genuinely means a free slot, because the connector never
|
||||
/// adds an empty channel to its list.
|
||||
ChannelSlotDecision decideChannelSlot({
|
||||
required List<Channel> channels,
|
||||
required int maxChannels,
|
||||
required bool isSyncing,
|
||||
}) {
|
||||
if (isSyncing) {
|
||||
return const ChannelSlotDecision.refused(ChannelSlotRefusal.syncing);
|
||||
}
|
||||
final used = channels.map((c) => c.index).toSet();
|
||||
for (var i = 0; i < maxChannels; i++) {
|
||||
if (!used.contains(i)) return ChannelSlotDecision.slot(i);
|
||||
}
|
||||
return const ChannelSlotDecision.refused(ChannelSlotRefusal.full);
|
||||
}
|
||||
@ -0,0 +1,107 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import 'channel_slot_decision.dart';
|
||||
import 'snack_bar_builder.dart';
|
||||
|
||||
/// A channel slot that is safe to write right now, or null after telling the
|
||||
/// user why not (#1021).
|
||||
///
|
||||
/// Every surface that adds a channel goes through this one function: the
|
||||
/// channels screen, the community QR scanner, and anything else that writes a
|
||||
/// slot. That is deliberate. The bug this fixes existed because the same
|
||||
/// question ("which slot is free?") was answered three different ways in three
|
||||
/// files, and only one of them was wrong. One answer cannot drift.
|
||||
///
|
||||
/// Call it at the moment of the write and never earlier. The connector empties
|
||||
/// its channel list for the duration of a channel sync, and `setChannel` itself
|
||||
/// starts one, so a slot chosen before a dialog or a confirmation can point at
|
||||
/// an occupied slot by the time it is written.
|
||||
///
|
||||
/// The owner's ruling is that the unsafe write is blocked but the control stays
|
||||
/// live: a greyed-out button prevents the damage and tells the user nothing. So
|
||||
/// a refusal returns null *and* says what is wrong.
|
||||
int? allocateChannelSlotOrExplain(
|
||||
BuildContext context,
|
||||
MeshCoreConnector connector,
|
||||
) {
|
||||
final decision = decideChannelSlot(
|
||||
channels: connector.channels,
|
||||
maxChannels: connector.maxChannels,
|
||||
// Not hasLoadedChannels: that stays false after a FAILED sync while the
|
||||
// cached list is restored, so gating on it would make adding a channel
|
||||
// impossible on a flaky link. Busy also covers a write the radio has not
|
||||
// answered yet (#1026): until it does, the list does not show its slot.
|
||||
isSyncing: connector.isChannelTableBusy,
|
||||
);
|
||||
switch (decision.refusal) {
|
||||
case ChannelSlotRefusal.syncing:
|
||||
showChannelBlockedMessage(context, context.l10n.channels_slotBusySyncing);
|
||||
return null;
|
||||
case ChannelSlotRefusal.full:
|
||||
showChannelBlockedMessage(
|
||||
context,
|
||||
context.l10n.channels_slotsAllFull(connector.maxChannels),
|
||||
);
|
||||
return null;
|
||||
case null:
|
||||
return decision.slot;
|
||||
}
|
||||
}
|
||||
|
||||
/// A refusal the user has to be able to read and act on, so it persists until
|
||||
/// dismissed.
|
||||
///
|
||||
/// `showDismissibleSnackBar` defaults to `persist: false` and a 4 second toast,
|
||||
/// which SAFELANE 6 rules out for an error.
|
||||
void showChannelBlockedMessage(BuildContext context, String message) {
|
||||
showDismissibleSnackBar(context, content: Text(message), persist: true);
|
||||
}
|
||||
|
||||
/// Explains a channel write the radio did not confirm, and returns true if it
|
||||
/// did. A caller shows its own success message only when this returns false,
|
||||
/// so nothing claims success before the radio has said OK (#1026).
|
||||
///
|
||||
/// A success toast shown after this would replace the explanation (a newer
|
||||
/// toast replaces the visible one), so callers must not show one.
|
||||
bool explainUnconfirmedChannelWrite(BuildContext context, ChannelWrite result) {
|
||||
final l10n = context.l10n;
|
||||
final message = switch (result) {
|
||||
ChannelWrite.ok => null,
|
||||
ChannelWrite.occupied => l10n.channels_writeOccupied,
|
||||
ChannelWrite.rejected => l10n.channels_writeRejected,
|
||||
ChannelWrite.noReply => l10n.channels_writeNoReply,
|
||||
ChannelWrite.clearedNotAdded => l10n.channels_writeClearedNotAdded,
|
||||
};
|
||||
if (message == null) return false;
|
||||
showChannelBlockedMessage(context, message);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Refuses a second Public channel, and says so. Returns true if it refused.
|
||||
///
|
||||
/// Public is identified by its PSK (`Channel.isPublicChannel`), not by slot 0,
|
||||
/// so it can live in any slot and this is the only duplicate check it needs.
|
||||
bool refusePublicAlreadyOnRadio(
|
||||
BuildContext context,
|
||||
MeshCoreConnector connector,
|
||||
) {
|
||||
if (!connector.channels.any((c) => c.isPublicChannel)) return false;
|
||||
showChannelBlockedMessage(context, context.l10n.channels_publicAlreadyAdded);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// For an edit or delete: refuses while the channel list is being re-read or
|
||||
/// a write is unanswered, and says so. Returns true if it refused.
|
||||
///
|
||||
/// Replies are matched to commands by order, so a write sent during a sync
|
||||
/// could take one of the sync's replies as its own.
|
||||
bool refuseWhileChannelTableBusy(
|
||||
BuildContext context,
|
||||
MeshCoreConnector connector,
|
||||
) {
|
||||
if (!connector.isChannelTableBusy) return false;
|
||||
showChannelBlockedMessage(context, context.l10n.channels_slotBusySyncing);
|
||||
return true;
|
||||
}
|
||||
@ -0,0 +1,128 @@
|
||||
// #1026 on top of #1063: what a confirmed channel write does to PSK-keyed
|
||||
// history.
|
||||
//
|
||||
// History is keyed by the channel's PSK (#194). Giving a slot to a different
|
||||
// channel is a reassignment: the old channel's history is kept, so it comes
|
||||
// back if that channel is ever re-added (#1063). Deleting a channel is the one
|
||||
// path that removes its history outright. Both happen only after the radio's
|
||||
// OK (#1026). Exercised through the real store, not the in-memory map.
|
||||
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
import 'package:meshcore_open/models/channel.dart';
|
||||
import 'package:meshcore_open/models/channel_message.dart';
|
||||
import 'package:meshcore_open/storage/channel_message_store.dart';
|
||||
import 'package:meshcore_open/storage/drift/blob_store.dart';
|
||||
import 'package:meshcore_open/storage/drift/offband_database.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
Uint8List psk(int fill) => Uint8List.fromList(List<int>.filled(16, fill));
|
||||
|
||||
List<int> channelInfo(int index, String name, Uint8List key) => [
|
||||
respCodeChannelInfo,
|
||||
index,
|
||||
...name.codeUnits,
|
||||
...List<int>.filled(32 - name.length, 0),
|
||||
...key,
|
||||
];
|
||||
|
||||
ChannelMessage msg(String text) => ChannelMessage(
|
||||
senderName: 's',
|
||||
text: text,
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(1000),
|
||||
isOutgoing: false,
|
||||
channelIndex: 0,
|
||||
messageId: text,
|
||||
);
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
late OffbandDatabase db;
|
||||
late MeshCoreConnector connector;
|
||||
|
||||
final weather = Channel(index: 0, name: 'Weather', psk: psk(0x22));
|
||||
|
||||
/// Reads the history stored under [weather]'s PSK, whatever slot it is in.
|
||||
late ChannelMessageStore weatherHistory;
|
||||
|
||||
Future<void> settle() => Future<void>.delayed(Duration.zero);
|
||||
void ok() => connector.handleFrameForTest([respCodeOk]);
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
db = OffbandDatabase(NativeDatabase.memory());
|
||||
BlobStore.overrideForTest(BlobStore(db));
|
||||
|
||||
connector = MeshCoreConnector();
|
||||
connector.sendFrameOverrideForTest = (_) {};
|
||||
connector.setConnectedForTest();
|
||||
connector.setSelfPublicKeyForTest(
|
||||
Uint8List.fromList(List<int>.generate(32, (i) => i)),
|
||||
);
|
||||
connector.wireMessageStoreForTest();
|
||||
|
||||
// The radio holds Weather in slot 0.
|
||||
await connector.getChannels(maxChannels: 1, force: true);
|
||||
connector.handleFrameForTest(channelInfo(0, weather.name, weather.psk));
|
||||
await settle();
|
||||
expect(connector.channels.single.pskHex, weather.pskHex);
|
||||
|
||||
weatherHistory = ChannelMessageStore()
|
||||
..setPublicKeyHex = connector.selfPublicKeyHex
|
||||
..channelPskResolver = (_) => weather.pskHex;
|
||||
await weatherHistory.saveChannelMessages(0, [msg('kept')]);
|
||||
expect(await weatherHistory.loadChannelMessages(0), hasLength(1));
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
BlobStore.clearTestOverride();
|
||||
await db.close();
|
||||
});
|
||||
|
||||
test(
|
||||
'a slot given to another channel keeps the old one\'s history',
|
||||
() async {
|
||||
final write = connector.setChannel(0, 'Other', psk(0x33), refresh: false);
|
||||
ok();
|
||||
|
||||
expect(await write, ChannelWrite.ok);
|
||||
expect(await weatherHistory.loadChannelMessages(0), hasLength(1));
|
||||
},
|
||||
);
|
||||
|
||||
test('a new key by edit keeps the old key\'s history too', () async {
|
||||
final edit = connector.editChannel(weather, 'Weather', psk(0x99));
|
||||
await settle();
|
||||
ok(); // the clear
|
||||
for (var i = 0; i < 50; i++) {
|
||||
await settle();
|
||||
}
|
||||
ok(); // the add
|
||||
|
||||
expect(await edit, ChannelWrite.ok);
|
||||
expect(await weatherHistory.loadChannelMessages(0), hasLength(1));
|
||||
});
|
||||
|
||||
test('a confirmed delete removes the channel\'s history', () async {
|
||||
final delete = connector.deleteChannel(0, refresh: false);
|
||||
ok();
|
||||
|
||||
expect(await delete, ChannelWrite.ok);
|
||||
expect(await weatherHistory.loadChannelMessages(0), isEmpty);
|
||||
});
|
||||
|
||||
test('a refused delete keeps it', () async {
|
||||
final delete = connector.deleteChannel(0, refresh: false);
|
||||
connector.handleFrameForTest([respCodeErr, errCodeNotFound]);
|
||||
|
||||
expect(await delete, ChannelWrite.rejected);
|
||||
expect(await weatherHistory.loadChannelMessages(0), hasLength(1));
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,321 @@
|
||||
// #1026 (epic #1021): a channel write waits for the radio's OK or ERR, and a
|
||||
// slot's message history is cleared only once the radio has said OK.
|
||||
//
|
||||
// Firmware with OffbandMesh/meshcore-firmware#1864 refuses a different channel
|
||||
// over an occupied slot with ERR_CODE_BAD_STATE and keeps that channel intact.
|
||||
// Clearing its history on the strength of having sent the frame would lose it.
|
||||
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
import 'package:meshcore_open/helpers/channel_slot_decision.dart';
|
||||
import 'package:meshcore_open/models/channel.dart';
|
||||
import 'package:meshcore_open/storage/drift/blob_store.dart';
|
||||
import 'package:meshcore_open/storage/drift/offband_database.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
Uint8List psk(int fill) => Uint8List.fromList(List<int>.filled(16, fill));
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
late OffbandDatabase db;
|
||||
late MeshCoreConnector connector;
|
||||
late List<Uint8List> sent;
|
||||
|
||||
List<Uint8List> setFrames() =>
|
||||
sent.where((f) => f.isNotEmpty && f[0] == cmdSetChannel).toList();
|
||||
|
||||
void ok() => connector.handleFrameForTest([respCodeOk]);
|
||||
void err(int code) => connector.handleFrameForTest([respCodeErr, code]);
|
||||
|
||||
/// The second write of a clear-then-add goes out only after the first has
|
||||
/// been answered and its history cleared, which takes real async time.
|
||||
Future<void> untilSetFrames(int count) async {
|
||||
for (var i = 0; i < 2000 && setFrames().length < count; i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 1));
|
||||
}
|
||||
expect(setFrames(), hasLength(count));
|
||||
}
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
db = OffbandDatabase(NativeDatabase.memory());
|
||||
BlobStore.overrideForTest(BlobStore(db));
|
||||
connector = MeshCoreConnector();
|
||||
connector.setConnectedForTest();
|
||||
sent = [];
|
||||
connector.sendFrameOverrideForTest = sent.add;
|
||||
connector.channelMessagesForTest[3] = [];
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
await db.close();
|
||||
BlobStore.clearTestOverride();
|
||||
});
|
||||
|
||||
group('setChannel', () {
|
||||
test('OK clears the slot\'s old history and reports ok', () async {
|
||||
final write = connector.setChannel(
|
||||
3,
|
||||
'Weather',
|
||||
psk(0x22),
|
||||
refresh: false,
|
||||
);
|
||||
ok();
|
||||
|
||||
expect(await write, ChannelWrite.ok);
|
||||
expect(connector.channelMessagesForTest.containsKey(3), isFalse);
|
||||
});
|
||||
|
||||
test('BAD_STATE is occupied, and the history stays', () async {
|
||||
final write = connector.setChannel(
|
||||
3,
|
||||
'Weather',
|
||||
psk(0x22),
|
||||
refresh: false,
|
||||
);
|
||||
err(errCodeBadState);
|
||||
|
||||
expect(await write, ChannelWrite.occupied);
|
||||
expect(connector.channelMessagesForTest.containsKey(3), isTrue);
|
||||
});
|
||||
|
||||
test('any other ERR is rejected, and the history stays', () async {
|
||||
final write = connector.setChannel(
|
||||
3,
|
||||
'Weather',
|
||||
psk(0x22),
|
||||
refresh: false,
|
||||
);
|
||||
err(errCodeNotFound);
|
||||
|
||||
expect(await write, ChannelWrite.rejected);
|
||||
expect(connector.channelMessagesForTest.containsKey(3), isTrue);
|
||||
});
|
||||
|
||||
test('no reply is noReply, and the history stays', () async {
|
||||
connector.channelWriteReplyTimeout = const Duration(milliseconds: 20);
|
||||
final write = connector.setChannel(
|
||||
3,
|
||||
'Weather',
|
||||
psk(0x22),
|
||||
refresh: false,
|
||||
);
|
||||
|
||||
expect(await write, ChannelWrite.noReply);
|
||||
expect(connector.channelMessagesForTest.containsKey(3), isTrue);
|
||||
});
|
||||
|
||||
test('a timed-out write cannot take the next write\'s reply', () async {
|
||||
connector.channelWriteReplyTimeout = const Duration(milliseconds: 20);
|
||||
expect(
|
||||
await connector.setChannel(3, 'A', psk(0x22), refresh: false),
|
||||
ChannelWrite.noReply,
|
||||
);
|
||||
|
||||
connector.channelWriteReplyTimeout = const Duration(seconds: 5);
|
||||
final second = connector.setChannel(4, 'B', psk(0x33), refresh: false);
|
||||
err(errCodeBadState);
|
||||
|
||||
expect(await second, ChannelWrite.occupied);
|
||||
});
|
||||
|
||||
test('the table is busy until the radio answers', () async {
|
||||
final write = connector.setChannel(
|
||||
3,
|
||||
'Weather',
|
||||
psk(0x22),
|
||||
refresh: false,
|
||||
);
|
||||
expect(connector.isChannelTableBusy, isTrue);
|
||||
|
||||
ok();
|
||||
await write;
|
||||
expect(connector.isChannelTableBusy, isFalse);
|
||||
});
|
||||
|
||||
test('disconnected sends nothing and reports noReply', () async {
|
||||
final fresh = MeshCoreConnector();
|
||||
fresh.sendFrameOverrideForTest = sent.add;
|
||||
|
||||
expect(
|
||||
await fresh.setChannel(3, 'Weather', psk(0x22)),
|
||||
ChannelWrite.noReply,
|
||||
);
|
||||
expect(sent, isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('deleteChannel', () {
|
||||
test('OK clears the history', () async {
|
||||
final delete = connector.deleteChannel(3, refresh: false);
|
||||
ok();
|
||||
|
||||
expect(await delete, ChannelWrite.ok);
|
||||
expect(connector.channelMessagesForTest.containsKey(3), isFalse);
|
||||
});
|
||||
|
||||
test('a refusal keeps the history', () async {
|
||||
final delete = connector.deleteChannel(3, refresh: false);
|
||||
err(errCodeNotFound);
|
||||
|
||||
expect(await delete, ChannelWrite.rejected);
|
||||
expect(connector.channelMessagesForTest.containsKey(3), isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('editChannel', () {
|
||||
final current = Channel(index: 3, name: 'Weather', psk: psk(0x22));
|
||||
|
||||
test('a rename is one write and keeps the history', () async {
|
||||
final edit = connector.editChannel(current, 'Wx', psk(0x22));
|
||||
ok();
|
||||
|
||||
expect(await edit, ChannelWrite.ok);
|
||||
expect(setFrames(), hasLength(1));
|
||||
expect(connector.channelMessagesForTest.containsKey(3), isTrue);
|
||||
});
|
||||
|
||||
test('a new key is clear-then-add, so #1864 firmware accepts it', () async {
|
||||
final edit = connector.editChannel(current, 'Weather', psk(0x99));
|
||||
await untilSetFrames(1);
|
||||
// The clear: an empty name.
|
||||
expect(setFrames()[0][2], 0);
|
||||
ok();
|
||||
|
||||
await untilSetFrames(2);
|
||||
expect(setFrames()[1].sublist(2 + 32, 2 + 32 + 16), psk(0x99));
|
||||
ok();
|
||||
|
||||
expect(await edit, ChannelWrite.ok);
|
||||
expect(connector.channelMessagesForTest.containsKey(3), isFalse);
|
||||
});
|
||||
|
||||
test('a refused clear writes nothing more and keeps the history', () async {
|
||||
final edit = connector.editChannel(current, 'Weather', psk(0x99));
|
||||
await untilSetFrames(1);
|
||||
err(errCodeNotFound);
|
||||
|
||||
expect(await edit, ChannelWrite.rejected);
|
||||
expect(setFrames(), hasLength(1));
|
||||
expect(connector.channelMessagesForTest.containsKey(3), isTrue);
|
||||
});
|
||||
|
||||
test(
|
||||
'a clear that lands and an add that fails says the slot is empty',
|
||||
() async {
|
||||
final edit = connector.editChannel(current, 'Weather', psk(0x99));
|
||||
await untilSetFrames(1);
|
||||
ok(); // the clear lands
|
||||
|
||||
await untilSetFrames(2);
|
||||
err(errCodeNotFound); // the add does not
|
||||
|
||||
expect(await edit, ChannelWrite.clearedNotAdded);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
// Gemini review of #1021: a sync started while a write waits for its reply
|
||||
// shares the reply queue with it, so the sync's empty-slot ERR could be
|
||||
// taken as the write's answer. The sync waits for the writes instead.
|
||||
group('a sync requested during a write', () {
|
||||
List<Uint8List> getFrames() =>
|
||||
sent.where((f) => f.isNotEmpty && f[0] == cmdGetChannel).toList();
|
||||
|
||||
test('is deferred until the reply, then runs', () async {
|
||||
final write = connector.setChannel(3, 'A', psk(0x22), refresh: false);
|
||||
await connector.getChannels(force: true);
|
||||
expect(connector.isSyncingChannels, isFalse);
|
||||
expect(getFrames(), isEmpty);
|
||||
|
||||
ok();
|
||||
expect(await write, ChannelWrite.ok);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(connector.isSyncingChannels, isTrue);
|
||||
expect(getFrames(), isNotEmpty);
|
||||
});
|
||||
|
||||
test('does not start between two writes of a batch', () async {
|
||||
final batch = connector.batchChannelWrites(() async {
|
||||
final first = connector.setChannel(3, 'A', psk(0x22), refresh: false);
|
||||
await connector.getChannels(force: true);
|
||||
ok();
|
||||
await first;
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
// Between the two writes: the deferred sync must not have started.
|
||||
expect(connector.isSyncingChannels, isFalse);
|
||||
final second = connector.setChannel(4, 'B', psk(0x33), refresh: false);
|
||||
ok();
|
||||
return second;
|
||||
});
|
||||
|
||||
expect(await batch, ChannelWrite.ok);
|
||||
expect(getFrames(), isNotEmpty, reason: 'runs once the batch ends');
|
||||
});
|
||||
|
||||
test('a write\'s own re-read waits for another pending write', () async {
|
||||
final first = connector.setChannel(3, 'A', psk(0x22));
|
||||
final second = connector.deleteChannel(4);
|
||||
|
||||
ok(); // answers the first; the second is still waiting
|
||||
expect(await first, ChannelWrite.ok);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(connector.isSyncingChannels, isFalse);
|
||||
expect(getFrames(), isEmpty);
|
||||
|
||||
ok();
|
||||
expect(await second, ChannelWrite.ok);
|
||||
expect(connector.isSyncingChannels, isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
// #1024: after a FAILED sync the cached list is restored but
|
||||
// hasLoadedChannels stays false. Gating adds on hasLoadedChannels would lock
|
||||
// the user out of adding channels on a flaky link, so the table has to read
|
||||
// as usable here, driven through the real sync rather than asserted.
|
||||
group('after a failed sync', () {
|
||||
List<int> channelInfo(int index, String name, int fill) => [
|
||||
respCodeChannelInfo,
|
||||
index,
|
||||
...name.codeUnits,
|
||||
...List<int>.filled(32 - name.length, 0),
|
||||
...psk(fill),
|
||||
];
|
||||
|
||||
Future<void> settle() => Future<void>.delayed(Duration.zero);
|
||||
|
||||
test(
|
||||
'the restored list is not busy, and an add gets a free slot',
|
||||
() async {
|
||||
await connector.getChannels(maxChannels: 2, force: true);
|
||||
connector.handleFrameForTest(channelInfo(0, 'Public', 0x11));
|
||||
await settle();
|
||||
connector.handleFrameForTest(channelInfo(1, 'Weather', 0x22));
|
||||
await settle();
|
||||
expect(connector.hasLoadedChannels, isTrue);
|
||||
|
||||
connector.sendFrameOverrideForTest = (_) =>
|
||||
throw Exception('link lost');
|
||||
await connector.getChannels(maxChannels: 2, force: true);
|
||||
await settle();
|
||||
|
||||
expect(connector.hasLoadedChannels, isFalse);
|
||||
expect(connector.channels.map((c) => c.index), unorderedEquals([0, 1]));
|
||||
expect(connector.isChannelTableBusy, isFalse);
|
||||
final decision = decideChannelSlot(
|
||||
channels: connector.channels,
|
||||
maxChannels: 3,
|
||||
isSyncing: connector.isChannelTableBusy,
|
||||
);
|
||||
expect(decision.slot, 2);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,181 @@
|
||||
// Channel slot allocation (#1021). Adding a channel could overwrite another,
|
||||
// including Public, losing it from the client and the radio.
|
||||
//
|
||||
// Three faults combined: the slot was chosen when the add dialog opened, the
|
||||
// connector empties its channel list during a sync so any index looked free,
|
||||
// and the chooser answered "no free slot" with slot 0, which is where Public
|
||||
// normally lives. These pin the decision so none of them can come back.
|
||||
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/helpers/channel_slot_decision.dart';
|
||||
import 'package:meshcore_open/models/channel.dart';
|
||||
|
||||
Channel _ch(int index, {String name = 'ch', String? pskHex}) => Channel(
|
||||
index: index,
|
||||
name: name,
|
||||
psk: Channel.parsePskHex(pskHex ?? '00112233445566778899aabbccddeeff'),
|
||||
);
|
||||
|
||||
void main() {
|
||||
group('decideChannelSlot', () {
|
||||
test('takes the lowest free slot', () {
|
||||
final d = decideChannelSlot(
|
||||
channels: [_ch(0), _ch(1), _ch(3)],
|
||||
maxChannels: 8,
|
||||
isSyncing: false,
|
||||
);
|
||||
expect(d.isAllowed, isTrue);
|
||||
expect(d.slot, 2);
|
||||
expect(d.refusal, isNull);
|
||||
});
|
||||
|
||||
test('takes slot 0 when the radio is empty', () {
|
||||
final d = decideChannelSlot(
|
||||
channels: const [],
|
||||
maxChannels: 8,
|
||||
isSyncing: false,
|
||||
);
|
||||
expect(d.slot, 0);
|
||||
});
|
||||
|
||||
test('refuses with full, NEVER slot 0, when every slot is used', () {
|
||||
final d = decideChannelSlot(
|
||||
channels: [for (var i = 0; i < 8; i++) _ch(i)],
|
||||
maxChannels: 8,
|
||||
isSyncing: false,
|
||||
);
|
||||
expect(d.isAllowed, isFalse);
|
||||
expect(d.refusal, ChannelSlotRefusal.full);
|
||||
expect(
|
||||
d.slot,
|
||||
isNull,
|
||||
reason: 'the old return 0 fallback is what destroyed Public',
|
||||
);
|
||||
});
|
||||
|
||||
test('refuses while syncing, even though every slot looks free', () {
|
||||
// This is the reported bug. Mid-sync the connector has emptied its list,
|
||||
// so an empty list plus a free-looking slot 0 is exactly the state that
|
||||
// overwrote Public.
|
||||
final d = decideChannelSlot(
|
||||
channels: const [],
|
||||
maxChannels: 8,
|
||||
isSyncing: true,
|
||||
);
|
||||
expect(d.isAllowed, isFalse);
|
||||
expect(d.refusal, ChannelSlotRefusal.syncing);
|
||||
expect(d.slot, isNull);
|
||||
});
|
||||
|
||||
test('syncing is refused even when a slot genuinely is free', () {
|
||||
final d = decideChannelSlot(
|
||||
channels: [_ch(0)],
|
||||
maxChannels: 8,
|
||||
isSyncing: true,
|
||||
);
|
||||
expect(d.refusal, ChannelSlotRefusal.syncing);
|
||||
});
|
||||
|
||||
test('syncing takes precedence over full', () {
|
||||
final d = decideChannelSlot(
|
||||
channels: [for (var i = 0; i < 8; i++) _ch(i)],
|
||||
maxChannels: 8,
|
||||
isSyncing: true,
|
||||
);
|
||||
expect(
|
||||
d.refusal,
|
||||
ChannelSlotRefusal.syncing,
|
||||
reason: 'a list being rewritten cannot be trusted to say it is full',
|
||||
);
|
||||
});
|
||||
|
||||
// The regression test for the gate I nearly got wrong. After a FAILED sync
|
||||
// the connector leaves hasLoadedChannels false but restores the cached
|
||||
// list into use. Gating on that flag would refuse forever on a flaky link,
|
||||
// so the decision takes isSyncing only, and a restored list allocates
|
||||
// normally.
|
||||
test('allocates normally after a failed sync, from the restored list', () {
|
||||
final d = decideChannelSlot(
|
||||
channels: [_ch(0), _ch(1)],
|
||||
maxChannels: 8,
|
||||
isSyncing: false,
|
||||
);
|
||||
expect(
|
||||
d.isAllowed,
|
||||
isTrue,
|
||||
reason: 'a failed sync must not disable adding channels',
|
||||
);
|
||||
expect(d.slot, 2);
|
||||
});
|
||||
|
||||
test('a single-slot radio can be filled and then refuses', () {
|
||||
expect(
|
||||
decideChannelSlot(
|
||||
channels: const [],
|
||||
maxChannels: 1,
|
||||
isSyncing: false,
|
||||
).slot,
|
||||
0,
|
||||
);
|
||||
expect(
|
||||
decideChannelSlot(
|
||||
channels: [_ch(0)],
|
||||
maxChannels: 1,
|
||||
isSyncing: false,
|
||||
).refusal,
|
||||
ChannelSlotRefusal.full,
|
||||
);
|
||||
});
|
||||
|
||||
test('an out-of-range index in the list does not block a free slot', () {
|
||||
// Defensive: a stale or odd index must not make the radio look full.
|
||||
final d = decideChannelSlot(
|
||||
channels: [_ch(99)],
|
||||
maxChannels: 4,
|
||||
isSyncing: false,
|
||||
);
|
||||
expect(d.slot, 0);
|
||||
});
|
||||
|
||||
test('Public holds no claim on slot 0, since it is identified by PSK', () {
|
||||
// `Channel.isPublicChannel` compares the PSK, not the index, so Public
|
||||
// can live anywhere and nothing may assume slot 0 belongs to it.
|
||||
final public = Channel(
|
||||
index: 3,
|
||||
name: 'Public',
|
||||
psk: Channel.parsePskHex(Channel.publicChannelPsk),
|
||||
);
|
||||
expect(public.isPublicChannel, isTrue);
|
||||
final d = decideChannelSlot(
|
||||
channels: [public],
|
||||
maxChannels: 8,
|
||||
isSyncing: false,
|
||||
);
|
||||
expect(d.slot, 0, reason: 'slot 0 is free here and may be used');
|
||||
});
|
||||
|
||||
test('a decision is either a slot or a refusal, never both', () {
|
||||
final allowed = decideChannelSlot(
|
||||
channels: const [],
|
||||
maxChannels: 4,
|
||||
isSyncing: false,
|
||||
);
|
||||
final refused = decideChannelSlot(
|
||||
channels: const [],
|
||||
maxChannels: 4,
|
||||
isSyncing: true,
|
||||
);
|
||||
expect(allowed.slot != null && allowed.refusal == null, isTrue);
|
||||
expect(refused.slot == null && refused.refusal != null, isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('Uint8List psk sanity', () {
|
||||
test('the helper builds channels with a real 16 byte psk', () {
|
||||
expect(_ch(0).psk, isA<Uint8List>());
|
||||
expect(_ch(0).psk.length, 16);
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,188 @@
|
||||
// #1024 (epic #1021): every channel refusal message shows on its own failure,
|
||||
// stays until dismissed, and is absent when the action is allowed.
|
||||
//
|
||||
// The messages are the whole point of the owner's ruling: block the unsafe
|
||||
// write, keep the control live, and say why. A message that never shows, or
|
||||
// that disappears in four seconds, is the silent failure that ruling rejects.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/helpers/channel_slot_ui.dart';
|
||||
import 'package:meshcore_open/l10n/app_localizations.dart';
|
||||
import 'package:meshcore_open/models/channel.dart';
|
||||
|
||||
class _FakeConn extends MeshCoreConnector {
|
||||
_FakeConn({this.list = const [], this.max = 40, this.busy = false});
|
||||
|
||||
final List<Channel> list;
|
||||
final int max;
|
||||
final bool busy;
|
||||
|
||||
@override
|
||||
List<Channel> get channels => list;
|
||||
@override
|
||||
int get maxChannels => max;
|
||||
@override
|
||||
bool get isChannelTableBusy => busy;
|
||||
}
|
||||
|
||||
Channel _ch(int index, String name, int fill) => Channel(
|
||||
index: index,
|
||||
name: name,
|
||||
psk: Channel.parsePskHex(List.filled(32, fill.toRadixString(16)).join()),
|
||||
);
|
||||
|
||||
final _l10n = lookupAppLocalizations(const Locale('en'));
|
||||
|
||||
/// Every refusal this file can show, so a success can assert none of them.
|
||||
final _allMessages = [
|
||||
_l10n.channels_slotBusySyncing,
|
||||
_l10n.channels_slotsAllFull(3),
|
||||
_l10n.channels_publicAlreadyAdded,
|
||||
_l10n.channels_writeOccupied,
|
||||
_l10n.channels_writeRejected,
|
||||
_l10n.channels_writeNoReply,
|
||||
_l10n.channels_writeClearedNotAdded,
|
||||
];
|
||||
|
||||
Future<BuildContext> _host(WidgetTester tester) async {
|
||||
late BuildContext context;
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: Builder(
|
||||
builder: (c) {
|
||||
context = c;
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
return context;
|
||||
}
|
||||
|
||||
/// Shown, and still shown well past the 4 second toast default.
|
||||
Future<void> _expectPersistent(WidgetTester tester, String message) async {
|
||||
await tester.pump();
|
||||
expect(find.text(message), findsOneWidget);
|
||||
await tester.pump(const Duration(seconds: 10));
|
||||
expect(find.text(message), findsOneWidget);
|
||||
}
|
||||
|
||||
Future<void> _expectNoRefusal(WidgetTester tester) async {
|
||||
await tester.pump();
|
||||
for (final message in _allMessages) {
|
||||
expect(find.text(message), findsNothing, reason: message);
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('allocateChannelSlotOrExplain', () {
|
||||
testWidgets('busy: refused, with the busy message', (tester) async {
|
||||
final context = await _host(tester);
|
||||
final slot = allocateChannelSlotOrExplain(context, _FakeConn(busy: true));
|
||||
|
||||
expect(slot, isNull);
|
||||
await _expectPersistent(tester, _l10n.channels_slotBusySyncing);
|
||||
});
|
||||
|
||||
testWidgets('full: refused, naming the slot count', (tester) async {
|
||||
final context = await _host(tester);
|
||||
final slot = allocateChannelSlotOrExplain(
|
||||
context,
|
||||
_FakeConn(
|
||||
list: [_ch(0, 'A', 1), _ch(1, 'B', 2), _ch(2, 'C', 3)],
|
||||
max: 3,
|
||||
),
|
||||
);
|
||||
|
||||
expect(slot, isNull);
|
||||
await _expectPersistent(tester, _l10n.channels_slotsAllFull(3));
|
||||
});
|
||||
|
||||
testWidgets('a free slot: allowed, and no message', (tester) async {
|
||||
final context = await _host(tester);
|
||||
final slot = allocateChannelSlotOrExplain(
|
||||
context,
|
||||
_FakeConn(list: [_ch(0, 'A', 1)], max: 3),
|
||||
);
|
||||
|
||||
expect(slot, 1);
|
||||
await _expectNoRefusal(tester);
|
||||
});
|
||||
});
|
||||
|
||||
group('refusePublicAlreadyOnRadio', () {
|
||||
testWidgets('Public present, in any slot: refused', (tester) async {
|
||||
final context = await _host(tester);
|
||||
final publicPsk = Channel.parsePskHex(Channel.publicChannelPsk);
|
||||
final refused = refusePublicAlreadyOnRadio(
|
||||
context,
|
||||
_FakeConn(
|
||||
list: [Channel(index: 5, name: 'Public', psk: publicPsk)],
|
||||
),
|
||||
);
|
||||
|
||||
expect(refused, isTrue);
|
||||
await _expectPersistent(tester, _l10n.channels_publicAlreadyAdded);
|
||||
});
|
||||
|
||||
testWidgets('no Public: allowed, and no message', (tester) async {
|
||||
final context = await _host(tester);
|
||||
final refused = refusePublicAlreadyOnRadio(
|
||||
context,
|
||||
_FakeConn(list: [_ch(0, 'A', 1)]),
|
||||
);
|
||||
|
||||
expect(refused, isFalse);
|
||||
await _expectNoRefusal(tester);
|
||||
});
|
||||
});
|
||||
|
||||
group('explainUnconfirmedChannelWrite', () {
|
||||
final cases = {
|
||||
ChannelWrite.occupied: _l10n.channels_writeOccupied,
|
||||
ChannelWrite.rejected: _l10n.channels_writeRejected,
|
||||
ChannelWrite.noReply: _l10n.channels_writeNoReply,
|
||||
ChannelWrite.clearedNotAdded: _l10n.channels_writeClearedNotAdded,
|
||||
};
|
||||
for (final entry in cases.entries) {
|
||||
testWidgets('${entry.key.name}: explained, persistently', (tester) async {
|
||||
final context = await _host(tester);
|
||||
|
||||
expect(explainUnconfirmedChannelWrite(context, entry.key), isTrue);
|
||||
await _expectPersistent(tester, entry.value);
|
||||
});
|
||||
}
|
||||
|
||||
testWidgets('ok: nothing to explain, and no message', (tester) async {
|
||||
final context = await _host(tester);
|
||||
|
||||
expect(explainUnconfirmedChannelWrite(context, ChannelWrite.ok), isFalse);
|
||||
await _expectNoRefusal(tester);
|
||||
});
|
||||
});
|
||||
|
||||
group('refuseWhileChannelTableBusy', () {
|
||||
testWidgets('busy: refused, with the busy message', (tester) async {
|
||||
final context = await _host(tester);
|
||||
|
||||
expect(
|
||||
refuseWhileChannelTableBusy(context, _FakeConn(busy: true)),
|
||||
isTrue,
|
||||
);
|
||||
await _expectPersistent(tester, _l10n.channels_slotBusySyncing);
|
||||
});
|
||||
|
||||
testWidgets('idle: allowed, and no message', (tester) async {
|
||||
final context = await _host(tester);
|
||||
|
||||
expect(refuseWhileChannelTableBusy(context, _FakeConn()), isFalse);
|
||||
await _expectNoRefusal(tester);
|
||||
});
|
||||
});
|
||||
}
|
||||
Loading…
Reference in new issue