task(#919): A2 DM save merges off the UI isolate

`MessageStore.saveMessages` had the same read-modify-write as the channel
store: decode the whole DM history, rebuild every record, re-encode it, all
on the UI isolate, for every single message that arrives.

Applies A1's helper. Only the incoming batch is encoded on the UI isolate;
the decode, merge and re-encode go to another isolate via
`mergeDmHistoryJson`, a top-level function so `compute` can send it. The
five JSON helpers it needs are now static for the same reason.

`mergeDmHistoryJson` throws on undecodable stored JSON rather than
swallowing it, which `mergeOffThread` turns into a refused write. That is
the same refusal the inline code made, and it is what stops a 5 MB history
being replaced by the one message that happened to arrive.

Tests: 6 added. Fixtures encode through the store's own encoder, never a
hand-written map, because a hand-rolled fixture rots the moment a non-null
field joins the schema. Includes a save round trip proving the second save
merges rather than overwrites (#343).

Citadel: meshcore-open-8sg
Refs #919, #917, #334

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
feat/919-blob-isolate
diffwireauto 1 month ago
parent aee1338636
commit 8592284fc2

@ -8,6 +8,36 @@ import '../utils/app_logger.dart';
import 'drift/blob_store.dart';
import 'prefs_manager.dart';
/// Merges a DM history blob with an incoming batch, entirely in JSON.
///
/// Top-level and free of any instance state so `compute` can send it to
/// another isolate (#919). Both arguments and the result are JSON strings, so
/// only two strings cross the isolate boundary rather than the object graph.
///
/// Throws if [stored] is not decodable. That is deliberate: `mergeOffThread`
/// turns the throw into a refused write, which keeps an unreadable blob intact
/// instead of replacing a whole history with just the incoming batch.
String mergeDmHistoryJson((String?, String) input) {
final (stored, incomingJson) = input;
final byKey = <String, Message>{};
if (stored != null && stored.isNotEmpty) {
for (final e in jsonDecode(stored) as List<dynamic>) {
final m = MessageStore._messageFromJson(e as Map<String, dynamic>);
byKey[MessageStore._mergeKey(m)] = m;
}
}
for (final e in jsonDecode(incomingJson) as List<dynamic>) {
final m = MessageStore._messageFromJson(e as Map<String, dynamic>);
byKey[MessageStore._mergeKey(m)] = m;
}
final merged = byKey.values.toList()
..sort((a, b) => a.timestamp.compareTo(b.timestamp));
return jsonEncode(merged.map(MessageStore._messageToJson).toList());
}
class MessageStore {
static const String _keyPrefix = 'messages_';
@ -31,34 +61,16 @@ class MessageStore {
// (removeMessage).
final key = '$keyFor$contactKeyHex';
final blobs = BlobStore.instance;
await blobs.synchronized(key, () async {
final byKey = <String, Message>{};
final existing = await blobs.readWithPrefsFallback(key);
if (existing != null && existing.isNotEmpty) {
try {
for (final e in jsonDecode(existing) as List<dynamic>) {
final m = _messageFromJson(e as Map<String, dynamic>);
byKey[_mergeKey(m)] = m;
}
} catch (e) {
appLogger.error(
'Failed to decode existing DM history before merge; aborting save '
'to avoid truncation: $e',
tag: 'Storage',
);
return;
}
}
for (final m in messages) {
byKey[_mergeKey(m)] = m;
}
final merged = byKey.values.toList()
..sort((a, b) => a.timestamp.compareTo(b.timestamp));
await blobs.write(key, jsonEncode(merged.map(_messageToJson).toList()));
});
// Same shape as the channel path (#919): only the INCOMING messages are
// encoded on the UI isolate; decoding the stored history, merging and
// re-encoding it happens on another isolate. `mergeOffThread` keeps the
// per-key serialisation and fails closed, so an undecodable blob is logged
// and left alone rather than overwritten by a truncated one.
final incoming = jsonEncode(messages.map(_messageToJson).toList());
await blobs.mergeOffThread(key, incoming, mergeDmHistoryJson);
}
String _mergeKey(Message m) {
static String _mergeKey(Message m) {
if (m.messageId.isNotEmpty) return 'id:${m.messageId}';
return 'x:${m.senderKeyHex}:${m.timestamp.millisecondsSinceEpoch}:${m.text}';
}
@ -144,7 +156,7 @@ class MessageStore {
await PrefsManager.instance.remove(key);
}
Map<String, dynamic> _messageToJson(Message msg) {
static Map<String, dynamic> _messageToJson(Message msg) {
return {
'senderKey': base64Encode(msg.senderKey),
'text': msg.text,
@ -181,7 +193,7 @@ class MessageStore {
};
}
Message _messageFromJson(Map<String, dynamic> json) {
static Message _messageFromJson(Map<String, dynamic> json) {
final rawText = json['text'] as String;
final isCli = json['isCli'] as bool? ?? false;
final decodedText = isCli

@ -1,11 +1,14 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/channel_message.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:shared_preferences/shared_preferences.dart';
@ -130,6 +133,115 @@ void main() {
);
});
Message dm(int i, {String? text}) => Message(
senderKey: Uint8List.fromList(const [1, 2, 3, 4]),
text: text ?? 'm$i',
timestamp: DateTime.fromMillisecondsSinceEpoch(1000 + i),
isOutgoing: false,
messageId: 'id$i',
);
Future<String> encodeDmVia(List<Message> ms) async {
final fixtureDb = OffbandDatabase(NativeDatabase.memory());
final previous = BlobStore.instance;
BlobStore.overrideForTest(BlobStore(fixtureDb));
try {
final store = MessageStore()..setPublicKeyHex = 'f' * 20;
await store.saveMessages('abcd', ms);
final keys = await BlobStore.instance.keysWithPrefix('messages_');
return (await BlobStore.instance.read(keys.single))!;
} finally {
BlobStore.overrideForTest(previous);
await fixtureDb.close();
}
}
group('mergeDmHistoryJson', () {
test('adds incoming messages to the stored history', () async {
final stored = await encodeDmVia([dm(1), dm(2)]);
final incoming = await encodeDmVia([dm(3)]);
final out =
jsonDecode(mergeDmHistoryJson((stored, incoming))) as List<dynamic>;
expect(out.length, 3);
expect(
out.map((e) => (e as Map<String, dynamic>)['messageId']),
containsAll(['id1', 'id2', 'id3']),
);
});
test('incoming wins on the same id, so a status change lands', () async {
final stored = await encodeDmVia([dm(1, text: 'original')]);
final incoming = await encodeDmVia([dm(1, text: 'edited')]);
final out =
jsonDecode(mergeDmHistoryJson((stored, incoming))) as List<dynamic>;
expect(
out.length,
1,
reason: 'same messageId must upsert, not duplicate',
);
expect((out.single as Map<String, dynamic>)['text'], 'edited');
});
test('result is sorted by timestamp regardless of input order', () async {
final stored = await encodeDmVia([dm(9), dm(3)]);
final incoming = await encodeDmVia([dm(5)]);
final out =
jsonDecode(mergeDmHistoryJson((stored, incoming))) as List<dynamic>;
final stamps = out
.map((e) => (e as Map<String, dynamic>)['timestamp'] as int)
.toList();
expect(stamps, [...stamps]..sort());
});
test(
'an empty or absent stored blob merges into just the incoming',
() async {
final incoming = await encodeDmVia([dm(1)]);
for (final stored in <String?>[null, '']) {
final out =
jsonDecode(mergeDmHistoryJson((stored, incoming)))
as List<dynamic>;
expect(out.length, 1, reason: 'stored=$stored');
}
},
);
test(
'THROWS on an undecodable stored blob rather than truncating',
() async {
final incoming = await encodeDmVia([dm(1)]);
expect(
() => mergeDmHistoryJson(('{not json at all', incoming)),
throwsA(anything),
);
},
);
test(
'a full DM save round trip through mergeOffThread keeps both',
() async {
final store = MessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveMessages('beef', [dm(1)]);
await store.saveMessages('beef', [dm(2)]);
final loaded = await store.loadMessages('beef');
expect(
loaded.map((m) => m.messageId),
['id1', 'id2'],
reason: 'the second save must merge, not overwrite (#343)',
);
},
);
});
group('BlobStore.mergeOffThread', () {
test('writes the merged result', () async {
final blobs = BlobStore.instance;
@ -214,6 +326,7 @@ void main() {
);
});
});
}
/// Top-level so `compute` can send it.

Loading…
Cancel
Save

Powered by TurnKey Linux.