Merge pull request #1168 from OffbandMesh/fix/1163-radio-switch-misfile
fix(#1163): a Bluetooth radio switch no longer files one radio's messages into anotherpull/1162/merge
commit
2e4e057832
@ -0,0 +1,199 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../utils/app_logger.dart';
|
||||
import 'drift/blob_store.dart';
|
||||
|
||||
/// One stored channel message, as the cleanup sees it.
|
||||
typedef ScannedRow = ({String storeKey, String mergeKey, int? rxTime});
|
||||
|
||||
/// What [findCrossRadioCopies] decided.
|
||||
class CopyDecision {
|
||||
const CopyDecision({required this.copies, required this.undecided});
|
||||
|
||||
/// Rows to hold aside: each is a copy whose original is on another radio.
|
||||
final List<ScannedRow> copies;
|
||||
|
||||
/// Copied messages left alone because no single radio can be shown to have
|
||||
/// received them.
|
||||
final int undecided;
|
||||
}
|
||||
|
||||
const _channelPrefix = 'channel_messages_';
|
||||
|
||||
String _radioOf(String storeKey) =>
|
||||
storeKey.substring(_channelPrefix.length, _channelPrefix.length + 10);
|
||||
|
||||
/// Finds channel messages that one radio received and a radio switch then
|
||||
/// wrote into another radio's history (#1163).
|
||||
///
|
||||
/// A copy keeps the original's receive time (`rxTime`) exactly. Two radios
|
||||
/// that each heard a packet deliver it at different moments, so the same
|
||||
/// message under two radios with the same receive time is one reception stored
|
||||
/// twice.
|
||||
///
|
||||
/// The original is on the radio that was connected when the message arrived.
|
||||
/// A radio's connected periods come from its own receptions: rows whose
|
||||
/// receive time no other radio shares. Runs of them with no gap longer than
|
||||
/// [gap] form a session, and a session covers [gap] either side. When exactly
|
||||
/// one of the radios holding a copy covers the receive time, the others hold
|
||||
/// copies. When none or several do, nothing is touched: the stored data cannot
|
||||
/// say which is real.
|
||||
///
|
||||
/// Run on a copy of the owner's Windows store (2,893 copied messages): 2,864
|
||||
/// rows held aside, 294 messages left alone. Every held row's original was
|
||||
/// kept, and none of the 257 held agent alerts, whose channel is known from
|
||||
/// their text, came from that channel.
|
||||
CopyDecision findCrossRadioCopies(
|
||||
List<ScannedRow> rows, {
|
||||
Duration gap = const Duration(minutes: 60),
|
||||
}) {
|
||||
final byMessage = <String, List<ScannedRow>>{};
|
||||
for (final r in rows) {
|
||||
if (r.rxTime == null || r.storeKey.length < _channelPrefix.length + 10) {
|
||||
continue;
|
||||
}
|
||||
byMessage.putIfAbsent(r.mergeKey, () => []).add(r);
|
||||
}
|
||||
|
||||
final ownReceptions = <String, List<int>>{};
|
||||
final copyGroups = <List<ScannedRow>>[];
|
||||
for (final group in byMessage.values) {
|
||||
final byTime = <int, List<ScannedRow>>{};
|
||||
for (final r in group) {
|
||||
byTime.putIfAbsent(r.rxTime!, () => []).add(r);
|
||||
}
|
||||
for (final entry in byTime.entries) {
|
||||
final radios = {for (final r in entry.value) _radioOf(r.storeKey)};
|
||||
if (radios.length > 1) {
|
||||
copyGroups.add(entry.value);
|
||||
} else {
|
||||
ownReceptions.putIfAbsent(radios.single, () => []).add(entry.key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final gapMs = gap.inMilliseconds;
|
||||
final sessions = <String, List<(int, int)>>{};
|
||||
ownReceptions.forEach((radio, times) {
|
||||
times.sort();
|
||||
final spans = <(int, int)>[];
|
||||
var start = times.first;
|
||||
var prev = times.first;
|
||||
for (final t in times.skip(1)) {
|
||||
if (t - prev > gapMs) {
|
||||
spans.add((start, prev));
|
||||
start = t;
|
||||
}
|
||||
prev = t;
|
||||
}
|
||||
spans.add((start, prev));
|
||||
sessions[radio] = spans;
|
||||
});
|
||||
|
||||
bool connectedAt(String radio, int t) {
|
||||
final spans = sessions[radio];
|
||||
if (spans == null) return false;
|
||||
var lo = 0;
|
||||
var hi = spans.length - 1;
|
||||
while (lo <= hi) {
|
||||
final mid = (lo + hi) >> 1;
|
||||
final (s, e) = spans[mid];
|
||||
if (t < s - gapMs) {
|
||||
hi = mid - 1;
|
||||
} else if (t > e + gapMs) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
final copies = <ScannedRow>[];
|
||||
var undecided = 0;
|
||||
for (final group in copyGroups) {
|
||||
final t = group.first.rxTime!;
|
||||
final radios = {for (final r in group) _radioOf(r.storeKey)};
|
||||
final connected = radios.where((radio) => connectedAt(radio, t)).toList();
|
||||
if (connected.length != 1) {
|
||||
undecided++;
|
||||
continue;
|
||||
}
|
||||
copies.addAll(group.where((r) => _radioOf(r.storeKey) != connected.single));
|
||||
}
|
||||
return CopyDecision(copies: copies, undecided: undecided);
|
||||
}
|
||||
|
||||
CopyDecision _decide(List<ScannedRow> rows) => findCrossRadioCopies(rows);
|
||||
|
||||
/// Runs [findCrossRadioCopies] once over the stored history and holds the
|
||||
/// copies aside (#1163).
|
||||
///
|
||||
/// Held, not deleted: each copy moves to [heldPrefix] + its original key, a key
|
||||
/// nothing reads, so a wrong call can be put back. A marker records the run so
|
||||
/// it happens once; the counts go to the log either way.
|
||||
class CrossRadioCopyCleanup {
|
||||
CrossRadioCopyCleanup._();
|
||||
|
||||
static const doneMarkerKey = '__cleanup_1163_cross_radio_copies';
|
||||
static const heldPrefix = 'held_1163_copy|';
|
||||
|
||||
static Future<void> run([BlobStore? store]) async {
|
||||
final blobs = store ?? BlobStore.instance;
|
||||
try {
|
||||
if (await blobs.read(doneMarkerKey) != null) return;
|
||||
final rows = await blobs.messageRowTimes(_channelPrefix);
|
||||
final decision = await compute(_decide, rows);
|
||||
|
||||
final byKey = <String, List<String>>{};
|
||||
for (final r in decision.copies) {
|
||||
byKey.putIfAbsent(r.storeKey, () => []).add(r.mergeKey);
|
||||
}
|
||||
var blobsHeld = 0;
|
||||
for (final entry in byKey.entries) {
|
||||
await blobs.moveMessageRows(
|
||||
entry.key,
|
||||
'$heldPrefix${entry.key}',
|
||||
entry.value,
|
||||
);
|
||||
// A key left with no rows reads its frozen pre-#920 blob instead,
|
||||
// which would put the copies straight back on screen. Rows are a
|
||||
// superset of that blob (the #952 gate), so when every row was a copy
|
||||
// the blob holds only copies: it is held aside too (review of #1163).
|
||||
if (await blobs.messageRowCount(entry.key) == 0) {
|
||||
final blob = await blobs.read(entry.key);
|
||||
if (blob != null) {
|
||||
await blobs.write('$heldPrefix${entry.key}', blob);
|
||||
await blobs.deleteEverywhere(entry.key);
|
||||
blobsHeld++;
|
||||
}
|
||||
}
|
||||
}
|
||||
await blobs.write(
|
||||
doneMarkerKey,
|
||||
jsonEncode({
|
||||
'at': DateTime.now().toIso8601String(),
|
||||
'held': decision.copies.length,
|
||||
'undecided': decision.undecided,
|
||||
'blobsHeld': blobsHeld,
|
||||
'keys': {for (final e in byKey.entries) e.key: e.value.length},
|
||||
}),
|
||||
);
|
||||
appLogger.info(
|
||||
'Cross-radio copy cleanup: scanned ${rows.length} channel messages, '
|
||||
'held aside ${decision.copies.length} copies from ${byKey.length} '
|
||||
'channel histories, left ${decision.undecided} undecided (#1163)',
|
||||
tag: 'Storage',
|
||||
);
|
||||
} catch (e) {
|
||||
// No marker is written, so the next launch tries again; the history is
|
||||
// untouched by a failed move, which runs in one transaction per key.
|
||||
appLogger.error(
|
||||
'Cross-radio copy cleanup failed and will retry next launch: $e',
|
||||
tag: 'Storage',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,107 @@
|
||||
// #1163: a channel write the radio did not answer is checked against a re-read
|
||||
// before the user is told it was not confirmed. A lost reply is not a lost
|
||||
// write; the owner was sent to fix channels that were in fact fine.
|
||||
|
||||
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/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 psk) => [
|
||||
respCodeChannelInfo,
|
||||
index,
|
||||
...name.codeUnits,
|
||||
...List<int>.filled(32 - name.length, 0),
|
||||
...psk,
|
||||
];
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
late OffbandDatabase db;
|
||||
late MeshCoreConnector c;
|
||||
|
||||
// What the fake radio holds per slot. It answers every channel read and
|
||||
// never answers a channel write: the reply was lost.
|
||||
late Map<int, (String, Uint8List)> radio;
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
db = OffbandDatabase(NativeDatabase.memory());
|
||||
BlobStore.overrideForTest(BlobStore(db));
|
||||
radio = {};
|
||||
c = MeshCoreConnector();
|
||||
c.setConnectedForTest();
|
||||
c.channelWriteReplyTimeout = const Duration(milliseconds: 20);
|
||||
c.sendFrameOverrideForTest = (frame) {
|
||||
if (frame.isEmpty || frame[0] != cmdGetChannel) return;
|
||||
final index = frame[1];
|
||||
final (name, psk) = radio[index] ?? ('', Uint8List(16));
|
||||
Future<void>.microtask(
|
||||
() => c.handleFrameForTest(_channelInfo(index, name, psk)),
|
||||
);
|
||||
};
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
await db.close();
|
||||
BlobStore.clearTestOverride();
|
||||
});
|
||||
|
||||
group('an add with no reply', () {
|
||||
test('is reported done when the re-read shows the channel', () async {
|
||||
radio[3] = ('Weather', _psk(0x22)); // the write landed
|
||||
|
||||
final result = await c.setChannel(3, 'Weather', _psk(0x22));
|
||||
|
||||
expect(result, ChannelWrite.ok);
|
||||
});
|
||||
|
||||
test('is still not confirmed when the re-read does not show it', () async {
|
||||
final result = await c.setChannel(3, 'Weather', _psk(0x22));
|
||||
|
||||
expect(result, ChannelWrite.noReply);
|
||||
});
|
||||
});
|
||||
|
||||
test('a disconnect during the re-read ends the wait at once', () async {
|
||||
// The radio goes quiet: no reply to the write, none to the re-read.
|
||||
c.sendFrameOverrideForTest = (_) {};
|
||||
final write = c.setChannel(3, 'Weather', _psk(0x22));
|
||||
await Future<void>.delayed(const Duration(milliseconds: 60));
|
||||
expect(c.isSyncingChannels, isTrue, reason: 'the re-read is running');
|
||||
|
||||
await c.disconnect(manual: true);
|
||||
|
||||
expect(
|
||||
await write.timeout(const Duration(seconds: 5)),
|
||||
ChannelWrite.noReply,
|
||||
reason: 'before the fix this waited out the 30 s guard',
|
||||
);
|
||||
});
|
||||
|
||||
group('a delete with no reply', () {
|
||||
test('is reported done when the re-read shows the slot empty', () async {
|
||||
final result = await c.deleteChannel(3);
|
||||
|
||||
expect(result, ChannelWrite.ok);
|
||||
});
|
||||
|
||||
test('is still not confirmed when the channel is still there', () async {
|
||||
radio[3] = ('Weather', _psk(0x22));
|
||||
|
||||
final result = await c.deleteChannel(3);
|
||||
|
||||
expect(result, ChannelWrite.noReply);
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,264 @@
|
||||
// #1163: switching radios over Bluetooth copied the previous radio's channel
|
||||
// messages into the next radio's history.
|
||||
//
|
||||
// #472 put the in-memory clear in _resetConnectionHandshakeState, but the
|
||||
// native Bluetooth connect only ran that on the web. Radio A's messages stayed
|
||||
// in memory under their slot numbers; the next message on the same slot from
|
||||
// radio B saved the whole list into B's channel for that slot. The owner's
|
||||
// Windows store held 2,893 such copies, each with the same receive time under
|
||||
// two radios.
|
||||
//
|
||||
// These tests go through the real connect, not the reset, because the old #472
|
||||
// test called the reset directly and passed while Bluetooth never ran it.
|
||||
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter_blue_plus/flutter_blue_plus.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/services/message_retry_service.dart';
|
||||
import 'package:meshcore_open/services/path_history_service.dart';
|
||||
import 'package:meshcore_open/services/storage_service.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 _channelInfoFrame(Channel ch) {
|
||||
final frame = Uint8List(50);
|
||||
frame[0] = respCodeChannelInfo;
|
||||
frame[1] = ch.index;
|
||||
final nameBytes = ch.name.codeUnits;
|
||||
for (var i = 0; i < nameBytes.length && i < 31; i++) {
|
||||
frame[2 + i] = nameBytes[i];
|
||||
}
|
||||
frame.setRange(34, 50, ch.psk);
|
||||
return frame;
|
||||
}
|
||||
|
||||
Uint8List _channelMsgFrame({required int channelIdx, required String text}) {
|
||||
return Uint8List.fromList([
|
||||
respCodeChannelMsgRecvV3,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
channelIdx,
|
||||
1,
|
||||
txtTypePlain,
|
||||
0x40,
|
||||
0xE2,
|
||||
0x01,
|
||||
0x00,
|
||||
...text.codeUnits,
|
||||
]);
|
||||
}
|
||||
|
||||
Channel _channel(int index, String name, int pskSeed) => Channel(
|
||||
index: index,
|
||||
name: name,
|
||||
psk: Uint8List.fromList(List<int>.generate(16, (i) => (pskSeed + i) & 0xFF)),
|
||||
);
|
||||
|
||||
Future<void> _settle([int turns = 25]) async {
|
||||
for (var i = 0; i < turns; i++) {
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
}
|
||||
}
|
||||
|
||||
final _radioA = Uint8List.fromList(List<int>.generate(32, (i) => i));
|
||||
final _radioB = Uint8List.fromList(List<int>.generate(32, (i) => 99 + i));
|
||||
|
||||
String _hex(Uint8List key) =>
|
||||
key.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late OffbandDatabase db;
|
||||
late MeshCoreConnector c;
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
db = OffbandDatabase(NativeDatabase.memory());
|
||||
BlobStore.overrideForTest(BlobStore(db));
|
||||
|
||||
c = MeshCoreConnector();
|
||||
c.initialize(
|
||||
retryService: MessageRetryService(),
|
||||
pathHistoryService: PathHistoryService(StorageService()),
|
||||
);
|
||||
c.sendFrameOverrideForTest = (_) {};
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
BlobStore.clearTestOverride();
|
||||
await db.close();
|
||||
});
|
||||
|
||||
// [savedList] is what the connect-time startup load reads back for a radio
|
||||
// this app has used before: its own last confirmed channel list.
|
||||
Future<void> becomeRadio(
|
||||
Uint8List key,
|
||||
List<Channel> layout, {
|
||||
List<Channel>? savedList,
|
||||
}) async {
|
||||
c.setConnectedForTest();
|
||||
c.setSelfPublicKeyForTest(key);
|
||||
c.wireMessageStoreForTest();
|
||||
if (savedList != null) c.seedCachedChannelsForTest(savedList);
|
||||
await c.getChannels(force: true, maxChannels: layout.length);
|
||||
for (final ch in layout) {
|
||||
c.handleFrameForTest(_channelInfoFrame(ch));
|
||||
await _settle(2);
|
||||
}
|
||||
await _settle();
|
||||
}
|
||||
|
||||
// The radio switch the owner does: drop radio A, connect radio B over
|
||||
// Bluetooth. The fake device cannot actually connect in a test; what matters
|
||||
// is everything the connect does before it reaches the radio.
|
||||
Future<void> switchOverBluetooth() async {
|
||||
await c.disconnect(manual: true);
|
||||
try {
|
||||
await c
|
||||
.connect(BluetoothDevice.fromId('00:11:22:33:44:55'))
|
||||
.timeout(const Duration(seconds: 5));
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<List<String>> storedTexts(Uint8List radio, Channel ch) async {
|
||||
final store = ChannelMessageStore()
|
||||
..setPublicKeyHex = _hex(radio)
|
||||
..channelPskResolver = ((_) => ch.pskHex);
|
||||
return (await store.loadChannelMessages(
|
||||
ch.index,
|
||||
)).map((m) => m.text).toList();
|
||||
}
|
||||
|
||||
test("a Bluetooth connect drops the previous radio's channel and DM history "
|
||||
'from memory', () async {
|
||||
final alpha = _channel(0, 'Alpha', 10);
|
||||
await becomeRadio(_radioA, [alpha]);
|
||||
c.handleFrameForTest(_channelMsgFrame(channelIdx: 0, text: 'A: one'));
|
||||
await _settle();
|
||||
c.conversationsForTest['deadbeef00'] = [];
|
||||
c.loadedConversationKeysForTest.add('deadbeef00');
|
||||
expect(c.channelMessagesForTest[0], isNotEmpty);
|
||||
|
||||
await switchOverBluetooth();
|
||||
|
||||
expect(c.channelMessagesForTest, isEmpty);
|
||||
expect(c.conversationsForTest, isEmpty);
|
||||
expect(c.loadedConversationKeysForTest, isEmpty);
|
||||
expect(
|
||||
c.channels,
|
||||
isEmpty,
|
||||
reason: "radio A's channel list must not answer for radio B's slots",
|
||||
);
|
||||
expect(c.cachedChannels, isEmpty);
|
||||
});
|
||||
|
||||
test("returning to radio B never saves radio A's messages into B's channel on "
|
||||
'the same slot', () async {
|
||||
final alpha = _channel(0, 'Alpha', 10);
|
||||
final gamma = _channel(0, 'Gamma', 70);
|
||||
|
||||
await becomeRadio(_radioA, [alpha]);
|
||||
c.handleFrameForTest(_channelMsgFrame(channelIdx: 0, text: 'A: from A'));
|
||||
await _settle();
|
||||
|
||||
// Radio B has been used before, so its saved list already says slot 0 is
|
||||
// Gamma. The post-sync check then sees no change on slot 0 and keeps
|
||||
// whatever is in memory there, which before the fix was radio A's history.
|
||||
await switchOverBluetooth();
|
||||
await becomeRadio(_radioB, [gamma], savedList: [gamma]);
|
||||
c.handleFrameForTest(_channelMsgFrame(channelIdx: 0, text: 'B: from B'));
|
||||
await _settle();
|
||||
|
||||
expect(
|
||||
await storedTexts(_radioB, gamma),
|
||||
['from B'],
|
||||
reason:
|
||||
"the bug: radio A's slot-0 message was saved into radio B's "
|
||||
'slot-0 channel',
|
||||
);
|
||||
expect(await storedTexts(_radioA, alpha), ['from A']);
|
||||
expect(
|
||||
(c.channelMessagesForTest[0] ?? const <ChannelMessage>[]).map(
|
||||
(m) => m.text,
|
||||
),
|
||||
['from B'],
|
||||
);
|
||||
});
|
||||
|
||||
test('a confirmed sync reloads a slot whose history was loaded under another '
|
||||
'channel, even when the saved list already matches the radio', () async {
|
||||
final alpha = _channel(0, 'Alpha', 10);
|
||||
final gamma = _channel(0, 'Gamma', 70);
|
||||
Future<void> storeHistory(Channel ch, String text) async {
|
||||
final store = ChannelMessageStore()
|
||||
..setPublicKeyHex = _hex(_radioB)
|
||||
..channelPskResolver = ((_) => ch.pskHex);
|
||||
await store.saveChannelMessages(ch.index, [
|
||||
ChannelMessage(
|
||||
senderName: 'X',
|
||||
text: text,
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(5000),
|
||||
isOutgoing: false,
|
||||
status: ChannelMessageStatus.sent,
|
||||
channelIndex: 0,
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
await storeHistory(alpha, 'alpha history');
|
||||
await storeHistory(gamma, 'gamma history');
|
||||
|
||||
c.setConnectedForTest();
|
||||
c.setSelfPublicKeyForTest(_radioB);
|
||||
c.wireMessageStoreForTest();
|
||||
// The window loads while slot 0 resolves to Alpha...
|
||||
c.seedCachedChannelsForTest([alpha]);
|
||||
await c.loadAllChannelMessages(maxChannels: 1);
|
||||
expect(c.channelMessagesForTest[0]!.map((m) => m.text), ['alpha history']);
|
||||
|
||||
// ...then the saved list says Gamma, and the radio confirms Gamma. The
|
||||
// saved-list diff sees no change on slot 0.
|
||||
await becomeRadio(_radioB, [gamma], savedList: [gamma]);
|
||||
await _settle();
|
||||
|
||||
expect(c.channelMessagesForTest[0]!.map((m) => m.text), ['gamma history']);
|
||||
});
|
||||
|
||||
test(
|
||||
'a new message saves only itself, never the rest of the window',
|
||||
() async {
|
||||
// Defense in depth: whatever else is in memory for a slot, right or wrong,
|
||||
// a new arrival must not write it into the channel's stored history.
|
||||
final gamma = _channel(0, 'Gamma', 70);
|
||||
await becomeRadio(_radioB, [gamma]);
|
||||
c.channelMessagesForTest[0] = [
|
||||
ChannelMessage(
|
||||
senderName: 'Elsewhere',
|
||||
text: 'stray, never stored here',
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(1000),
|
||||
isOutgoing: false,
|
||||
status: ChannelMessageStatus.sent,
|
||||
channelIndex: 0,
|
||||
),
|
||||
];
|
||||
|
||||
c.handleFrameForTest(_channelMsgFrame(channelIdx: 0, text: 'B: new'));
|
||||
await _settle();
|
||||
|
||||
expect(await storedTexts(_radioB, gamma), ['new']);
|
||||
},
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,187 @@
|
||||
// #1163: channel messages a Bluetooth radio switch copied into another radio's
|
||||
// history. A copy keeps the original's receive time exactly; the original is on
|
||||
// the radio that was connected when the message arrived.
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/storage/cross_radio_copy_cleanup.dart';
|
||||
import 'package:meshcore_open/storage/drift/blob_store.dart';
|
||||
import 'package:meshcore_open/storage/drift/offband_database.dart';
|
||||
|
||||
const _a = 'aaaaaaaaaa';
|
||||
const _b = 'bbbbbbbbbb';
|
||||
String _key(String radio, String psk) => 'channel_messages_${radio}psk_$psk';
|
||||
|
||||
const _min = 60 * 1000;
|
||||
const _t0 = 1_800_000_000_000;
|
||||
|
||||
ScannedRow _row(String storeKey, String mergeKey, int rxTime) =>
|
||||
(storeKey: storeKey, mergeKey: mergeKey, rxTime: rxTime);
|
||||
|
||||
// [radio] was connected around [at]: a few receptions only it holds.
|
||||
List<ScannedRow> _session(String radio, int at, String tag) => [
|
||||
for (var i = 0; i < 3; i++)
|
||||
_row(_key(radio, 'own'), '$tag-own-$i', at + i * _min),
|
||||
];
|
||||
|
||||
void main() {
|
||||
group('findCrossRadioCopies', () {
|
||||
test('the field pattern: radio A received it, radio B holds a copy', () {
|
||||
final rows = [
|
||||
..._session(_a, _t0, 'a'),
|
||||
..._session(_b, _t0 + 6 * 60 * _min, 'b'), // B connected 6 hours later
|
||||
_row(_key(_a, 'claude'), 'alert', _t0 + _min),
|
||||
_row(_key(_b, 'offband'), 'alert', _t0 + _min), // same slot on B
|
||||
];
|
||||
|
||||
final decision = findCrossRadioCopies(rows);
|
||||
|
||||
expect(decision.copies.map((r) => r.storeKey), [_key(_b, 'offband')]);
|
||||
expect(decision.undecided, 0);
|
||||
});
|
||||
|
||||
test('a message both radios heard, at different times, is no copy', () {
|
||||
final rows = [
|
||||
..._session(_a, _t0, 'a'),
|
||||
..._session(_b, _t0 + 6 * 60 * _min, 'b'),
|
||||
_row(_key(_a, 'public'), 'heard-twice', _t0 + _min),
|
||||
_row(_key(_b, 'public'), 'heard-twice', _t0 + 6 * 60 * _min + _min),
|
||||
];
|
||||
|
||||
final decision = findCrossRadioCopies(rows);
|
||||
|
||||
expect(decision.copies, isEmpty);
|
||||
expect(decision.undecided, 0);
|
||||
});
|
||||
|
||||
test(
|
||||
'a copy with no connection evidence on either radio is left alone',
|
||||
() {
|
||||
final rows = [
|
||||
..._session(_a, _t0, 'a'),
|
||||
..._session(_b, _t0 + 6 * 60 * _min, 'b'),
|
||||
// Three days away from both sessions: nothing says who heard it.
|
||||
_row(_key(_a, 'echo'), 'orphan', _t0 + 3 * 24 * 60 * _min),
|
||||
_row(_key(_b, 'test'), 'orphan', _t0 + 3 * 24 * 60 * _min),
|
||||
];
|
||||
|
||||
final decision = findCrossRadioCopies(rows);
|
||||
|
||||
expect(decision.copies, isEmpty);
|
||||
expect(decision.undecided, 1);
|
||||
},
|
||||
);
|
||||
|
||||
test('two radios both connected at that time: left alone', () {
|
||||
final rows = [
|
||||
..._session(_a, _t0, 'a'),
|
||||
..._session(_b, _t0, 'b'),
|
||||
_row(_key(_a, 'echo'), 'either', _t0 + _min),
|
||||
_row(_key(_b, 'test'), 'either', _t0 + _min),
|
||||
];
|
||||
|
||||
final decision = findCrossRadioCopies(rows);
|
||||
|
||||
expect(decision.copies, isEmpty);
|
||||
expect(decision.undecided, 1);
|
||||
});
|
||||
});
|
||||
|
||||
group('CrossRadioCopyCleanup.run', () {
|
||||
late OffbandDatabase db;
|
||||
late BlobStore blobs;
|
||||
|
||||
setUp(() {
|
||||
db = OffbandDatabase(NativeDatabase.memory());
|
||||
blobs = BlobStore(db);
|
||||
});
|
||||
|
||||
tearDown(() => db.close());
|
||||
|
||||
Future<void> store(String key, String mergeKey, int rxTime) =>
|
||||
blobs.upsertMessageRows(key, [
|
||||
MessageRowInput(
|
||||
mergeKey: mergeKey,
|
||||
timestampMs: rxTime,
|
||||
payload: jsonEncode({'text': mergeKey, 'rxTime': rxTime}),
|
||||
),
|
||||
]);
|
||||
|
||||
Future<void> seedFieldPattern() async {
|
||||
for (final r in [
|
||||
..._session(_a, _t0, 'a'),
|
||||
..._session(_b, _t0 + 6 * 60 * _min, 'b'),
|
||||
_row(_key(_a, 'claude'), 'alert', _t0 + _min),
|
||||
_row(_key(_b, 'offband'), 'alert', _t0 + _min),
|
||||
]) {
|
||||
await store(r.storeKey, r.mergeKey, r.rxTime!);
|
||||
}
|
||||
}
|
||||
|
||||
test(
|
||||
'holds the copy aside, keeps the original, and can be undone',
|
||||
() async {
|
||||
await seedFieldPattern();
|
||||
|
||||
await CrossRadioCopyCleanup.run(blobs);
|
||||
|
||||
expect(await blobs.messageMergeKeys(_key(_b, 'offband')), isEmpty);
|
||||
expect(await blobs.messageMergeKeys(_key(_a, 'claude')), {'alert'});
|
||||
final held =
|
||||
'${CrossRadioCopyCleanup.heldPrefix}${_key(_b, 'offband')}';
|
||||
expect(
|
||||
await blobs.messageMergeKeys(held),
|
||||
{'alert'},
|
||||
reason:
|
||||
'held, not deleted: the copy is kept where it can be put back',
|
||||
);
|
||||
final marker = jsonDecode(
|
||||
(await blobs.read(CrossRadioCopyCleanup.doneMarkerKey))!,
|
||||
);
|
||||
expect(marker['held'], 1);
|
||||
expect(marker['undecided'], 0);
|
||||
},
|
||||
);
|
||||
|
||||
test('a key left with no rows has its old blob held aside too, so the '
|
||||
'copies cannot come back from it', () async {
|
||||
await seedFieldPattern();
|
||||
// B's offband history from before rows (#920): the same copy, frozen.
|
||||
await blobs.write(
|
||||
_key(_b, 'offband'),
|
||||
jsonEncode([
|
||||
{'text': 'alert', 'rxTime': _t0 + _min},
|
||||
]),
|
||||
);
|
||||
|
||||
await CrossRadioCopyCleanup.run(blobs);
|
||||
|
||||
expect(await blobs.read(_key(_b, 'offband')), isNull);
|
||||
expect(
|
||||
await blobs.read(
|
||||
'${CrossRadioCopyCleanup.heldPrefix}${_key(_b, 'offband')}',
|
||||
),
|
||||
isNotNull,
|
||||
reason: 'held, not deleted',
|
||||
);
|
||||
expect(await blobs.messageMergeKeys(_key(_a, 'claude')), {'alert'});
|
||||
});
|
||||
|
||||
test(
|
||||
'runs once: a later launch does not touch the history again',
|
||||
() async {
|
||||
await seedFieldPattern();
|
||||
await CrossRadioCopyCleanup.run(blobs);
|
||||
|
||||
// A new copy appearing afterwards is not this cleanup's business.
|
||||
await store(_key(_b, 'public'), 'later', _t0 + 2 * _min);
|
||||
await store(_key(_a, 'public'), 'later', _t0 + 2 * _min);
|
||||
await CrossRadioCopyCleanup.run(blobs);
|
||||
|
||||
expect(await blobs.messageMergeKeys(_key(_b, 'public')), {'later'});
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,192 @@
|
||||
// #1163: the owner asked for a way to start fresh for one radio, channels and
|
||||
// direct messages together, and for a channel clear that actually clears.
|
||||
// Clear Chat used to save an emptied list; saves merge (#343), so nothing was
|
||||
// deleted and the history came back on the next load.
|
||||
|
||||
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/models/channel.dart';
|
||||
import 'package:meshcore_open/models/channel_message.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
import 'package:meshcore_open/models/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/message_store.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:meshcore_open/storage/radio_data_wipe.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
final _radioA = Uint8List.fromList(List<int>.generate(32, (i) => i));
|
||||
const _radioAPrefix = '0001020304';
|
||||
const _radioBPrefix = '6364656667';
|
||||
|
||||
Channel _channel(int index, String name, int seed) => Channel(
|
||||
index: index,
|
||||
name: name,
|
||||
psk: Uint8List.fromList(List<int>.generate(16, (i) => (seed + i) & 0xFF)),
|
||||
);
|
||||
|
||||
ChannelMessage _chanMsg(String text) => ChannelMessage(
|
||||
senderName: 'X',
|
||||
text: text,
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(5000),
|
||||
isOutgoing: false,
|
||||
status: ChannelMessageStatus.sent,
|
||||
channelIndex: 0,
|
||||
);
|
||||
|
||||
Message _dm(String text) => Message(
|
||||
senderKey: Uint8List(32),
|
||||
text: text,
|
||||
timestamp: DateTime.fromMillisecondsSinceEpoch(5000),
|
||||
isOutgoing: false,
|
||||
);
|
||||
|
||||
ChannelMessageStore _chanStore(String radio, Channel ch) =>
|
||||
ChannelMessageStore()
|
||||
..setPublicKeyHex = radio
|
||||
..channelPskResolver = ((_) => ch.pskHex);
|
||||
|
||||
// MessageStore takes the radio's full key and keeps its first 10 hex; a bare
|
||||
// 10-hex prefix is refused and every save is skipped.
|
||||
MessageStore _dmStore(String radio) =>
|
||||
MessageStore()..setPublicKeyHex = '$radio${'0' * 54}';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
late OffbandDatabase db;
|
||||
final alpha = _channel(0, 'Alpha', 10);
|
||||
const contactKey =
|
||||
'aa00000000000000000000000000000000000000000000000000000000000000';
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
db = OffbandDatabase(NativeDatabase.memory());
|
||||
BlobStore.overrideForTest(BlobStore(db));
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
BlobStore.clearTestOverride();
|
||||
await db.close();
|
||||
});
|
||||
|
||||
Future<List<String>> chanTexts(String radio) async => (await _chanStore(
|
||||
radio,
|
||||
alpha,
|
||||
).loadChannelMessages(0)).map((m) => m.text).toList();
|
||||
Future<List<String>> dmTexts(String radio) async => (await _dmStore(
|
||||
radio,
|
||||
).loadMessages(contactKey)).map((m) => m.text).toList();
|
||||
|
||||
test("the per-radio wipe removes this radio's channel and DM history, and "
|
||||
"nothing of any other radio's", () async {
|
||||
for (final radio in [_radioAPrefix, _radioBPrefix]) {
|
||||
await _chanStore(radio, alpha).saveChannelMessages(0, [_chanMsg(radio)]);
|
||||
await _dmStore(radio).saveMessages(contactKey, [_dm(radio)]);
|
||||
}
|
||||
await BlobStore.instance.write('contacts$_radioAPrefix', '[]');
|
||||
expect(await dmTexts(_radioAPrefix), [_radioAPrefix]);
|
||||
expect(await dmTexts(_radioBPrefix), [_radioBPrefix]);
|
||||
|
||||
await wipeRadioMessageHistory(_radioAPrefix);
|
||||
|
||||
expect(await chanTexts(_radioAPrefix), isEmpty);
|
||||
expect(await dmTexts(_radioAPrefix), isEmpty);
|
||||
expect(await chanTexts(_radioBPrefix), [_radioBPrefix]);
|
||||
expect(await dmTexts(_radioBPrefix), [_radioBPrefix]);
|
||||
expect(
|
||||
await BlobStore.instance.read('contacts$_radioAPrefix'),
|
||||
'[]',
|
||||
reason: 'contacts are not message history and stay',
|
||||
);
|
||||
});
|
||||
|
||||
test('the per-radio wipe refuses anything but a 10-hex radio prefix', () {
|
||||
expect(() => wipeRadioMessageHistory(''), throwsArgumentError);
|
||||
expect(() => wipeRadioMessageHistory('0001'), throwsArgumentError);
|
||||
});
|
||||
|
||||
group('connector', () {
|
||||
late MeshCoreConnector c;
|
||||
|
||||
setUp(() {
|
||||
c = MeshCoreConnector();
|
||||
c.setConnectedForTest();
|
||||
c.setSelfPublicKeyForTest(_radioA);
|
||||
c.wireMessageStoreForTest();
|
||||
c.seedCachedChannelsForTest([alpha]);
|
||||
});
|
||||
|
||||
test(
|
||||
'deleting message history for this radio empties the screen too',
|
||||
() async {
|
||||
await _chanStore(
|
||||
_radioAPrefix,
|
||||
alpha,
|
||||
).saveChannelMessages(0, [_chanMsg('old')]);
|
||||
await c.loadAllChannelMessages(maxChannels: 1);
|
||||
expect(c.channelMessagesForTest[0], isNotEmpty);
|
||||
|
||||
expect(await c.deleteMessageHistoryForThisRadio(), isNull);
|
||||
|
||||
expect(c.channelMessagesForTest, isEmpty);
|
||||
expect(await chanTexts(_radioAPrefix), isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'deleting message history with no radio connected is refused',
|
||||
() async {
|
||||
final idle = MeshCoreConnector();
|
||||
|
||||
expect(
|
||||
await idle.deleteMessageHistoryForThisRadio(),
|
||||
HistoryWipeRefusal.notConnected,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('Clear Chat on a channel deletes its stored history', () async {
|
||||
await _chanStore(
|
||||
_radioAPrefix,
|
||||
alpha,
|
||||
).saveChannelMessages(0, [_chanMsg('old')]);
|
||||
await c.loadAllChannelMessages(maxChannels: 1);
|
||||
|
||||
await c.clearChannelHistory(alpha);
|
||||
await c.loadAllChannelMessages(maxChannels: 1);
|
||||
|
||||
expect(
|
||||
c.channelMessagesForTest[0] ?? const <ChannelMessage>[],
|
||||
isEmpty,
|
||||
reason: 'the bug: the history came back on the next load',
|
||||
);
|
||||
expect(await chanTexts(_radioAPrefix), isEmpty);
|
||||
});
|
||||
|
||||
test('Clear Chat on a contact deletes the stored conversation', () async {
|
||||
await _dmStore(_radioAPrefix).saveMessages(contactKey, [_dm('old')]);
|
||||
expect(await dmTexts(_radioAPrefix), ['old']);
|
||||
final contact = Contact(
|
||||
publicKey: Uint8List.fromList(
|
||||
List<int>.generate(32, (i) => i == 0 ? 0xAA : 0),
|
||||
),
|
||||
receivedName: 'Friend',
|
||||
type: 1,
|
||||
pathLength: -1,
|
||||
path: Uint8List(0),
|
||||
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
|
||||
);
|
||||
|
||||
await c.clearMessagesForContact(contact);
|
||||
|
||||
expect(await dmTexts(_radioAPrefix), isEmpty);
|
||||
});
|
||||
});
|
||||
}
|
||||
Loading…
Reference in new issue