task(#920): B2 both message stores read and write rows

A save is now one upsert per message in the list being saved, and costs the
same with 50,000 messages of history as with 50. That is the Feature's
"done when", and it is the part #919 could not deliver.

Also gone: a delete is a single-row DELETE instead of rewriting the whole
history, and a load reads only its own key's rows, ordered and pageable in
SQLite.

Load order matters and is deliberate. Rows are consulted first, but ONLY
when rows actually exist. A key marked migrated with no rows still falls
through to the legacy slot-index and unscoped-key adoption (#194, #306),
because those run on blobs; short-circuiting on the marker alone would strand
history stored under an older key. Adoption then hands its result to the
migration, so the key ends up on rows either way.

The blob path stays as the fallback for a key whose migration was refused.
Refused keys keep working exactly as they did after #919: off the UI isolate,
merge-not-overwrite, failing closed on an undecodable blob. Tested, including
that a refused key does not accumulate half a history in rows.

One unreadable row now costs one message. On the blob a single bad byte took
the whole conversation with it.

Clear paths had to learn about rows: a cleared channel or conversation that
only dropped its blob would have stayed fully readable. clearAll also sweeps
row-only keys, which no longer appear in a blob key listing.

`encodeHistoryForTest` is new on both stores. The #919 tests built their
blob fixtures by saving through the store and reading the blob back, which
cannot work once saves write rows, and hand-written fixtures are what rotted
the first time. They now call the stores' own encoder directly.

Tests: 24 added, through the public store API only, because that is what an
existing install hits on its first launch after this ships. Covered: blob
adoption on first load and on first save, the windowed-save truncation case
(#343), per-radio and per-contact scoping (#472), delete, clear, clearAll on
row-only keys, a refused migration still serving reads and writes, and the
payload being the stores' own encoding.

Suite: 1,344 pass, analyze clean, format clean.

Citadel: meshcore-open-tfq
Refs #920, #917, #334

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
feat/920-message-rows
diffwireauto 1 month ago
parent cee863dbf6
commit 2a6d135b97

@ -1,5 +1,5 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:meshcore_open/utils/app_logger.dart';
import '../models/channel_message.dart';
@ -76,6 +76,30 @@ String? dropFromChannelHistoryJson((String?, String) input) {
return jsonEncode(kept.map(ChannelMessageStore._messageToJson).toList());
}
/// Converts a whole channel-history blob into one row per message (#920).
///
/// Top-level so `compute` can send it. Returns exactly one row per element of
/// the source array, with no dedupe and no sorting: the migration's gate
/// compares this count against an independent count of the blob, and does its
/// own deduping, so doing either here would defeat the check.
///
/// Throws on undecodable JSON, which the migration turns into a refusal that
/// leaves the blob as the source of truth.
List<MessageRowInput> channelHistoryToRows(String blobJson) {
return (jsonDecode(blobJson) as List<dynamic>).map((e) {
final map = e as Map<String, dynamic>;
final m = ChannelMessageStore._messageFromJson(map);
return MessageRowInput(
mergeKey: ChannelMessageStore._mergeKey(m),
timestampMs: m.timestamp.millisecondsSinceEpoch,
// The source map, re-encoded, NOT a re-serialisation of the decoded
// object. A round trip through the model would quietly rewrite any field
// the model defaults, and this is a move, not a rewrite.
payload: jsonEncode(map),
);
}).toList();
}
class ChannelMessageStore {
static const String _keyPrefix = 'channel_messages_';
@ -143,19 +167,42 @@ class ChannelMessageStore {
// resurrects a message the user deleted.
final key = _storageKey(channelIndex);
final blobs = BlobStore.instance;
// Only the INCOMING messages are encoded here, on the UI isolate: that is
// normally one message and costs microseconds. Decoding the stored history,
// merging and re-encoding it runs on another isolate (#919), because at the
// owner's largest channel (5.38 MB, 9,230 messages) that work measured
// 134 ms per save and a burst of them crossed Android's five-second
// watchdog (#334). `mergeOffThread` keeps the per-key serialisation that
// Rows (#920): one upsert per message in the list, which costs the same
// whether 50 or 50,000 messages are already stored. #919 moved the
// whole-history re-encode to another isolate; this removes it. The cost is
// proportional to the in-memory window being saved, never to the history.
if (await blobs.ensureMessageRowsMigrated(key, channelHistoryToRows)) {
await blobs.upsertMessageRows(key, messages.map(_toRow));
return;
}
// Blob fallback, for a key whose migration was refused. Still correct,
// still off the UI isolate (#919): only the INCOMING messages are encoded
// here, and decoding the stored history, merging and re-encoding it runs on
// another isolate. `mergeOffThread` keeps the per-key serialisation that
// stops two saves clobbering each other, and fails closed: if the stored
// JSON will not decode, the key is not written, which is the same refusal
// this code made inline.
// JSON will not decode, the key is not written.
final incoming = jsonEncode(messages.map(_messageToJson).toList());
await blobs.mergeOffThread(key, incoming, mergeChannelHistoryJson);
}
static MessageRowInput _toRow(ChannelMessage m) => MessageRowInput(
mergeKey: _mergeKey(m),
timestampMs: m.timestamp.millisecondsSinceEpoch,
payload: jsonEncode(_messageToJson(m)),
);
/// The store's own history encoding, for tests that need a blob fixture.
///
/// Exists so a test never hand-writes one: a hand-rolled fixture rots the
/// moment a non-null field joins the schema, which is exactly how the #919
/// tests first failed. Saving through [saveChannelMessages] cannot serve that
/// purpose any more, because saves write rows now.
@visibleForTesting
static String encodeHistoryForTest(List<ChannelMessage> messages) =>
jsonEncode(messages.map(_messageToJson).toList());
/// Stable identity for merge/dedupe. messageId when present, else a composite
/// that distinguishes distinct messages that share no id.
static String _mergeKey(ChannelMessage m) {
@ -174,17 +221,23 @@ class ChannelMessageStore {
/// path (#343): save merges and never removes, so deletion cannot go through
/// save.
///
/// Decode and re-encode run off the UI isolate for the same reason saving
/// does (#919): a delete rewrites the whole blob, so on a large channel it
/// blocked the UI for as long as a save did, right when the user had just
/// tapped something.
/// On rows this is a single-row DELETE (#920). On the blob fallback the
/// decode and re-encode run off the UI isolate (#919), because a delete
/// rewrites the whole blob and so blocked the UI for as long as a save did,
/// right when the user had just tapped something.
Future<void> removeChannelMessage(
int channelIndex,
ChannelMessage message,
) async {
if (publicKeyHex.isEmpty) return;
await BlobStore.instance.mergeOffThread(
_storageKey(channelIndex),
final key = _storageKey(channelIndex);
final blobs = BlobStore.instance;
if (await blobs.ensureMessageRowsMigrated(key, channelHistoryToRows)) {
await blobs.deleteMessageRow(key, _mergeKey(message));
return;
}
await blobs.mergeOffThread(
key,
_mergeKey(message),
dropFromChannelHistoryJson,
);
@ -200,6 +253,19 @@ class ChannelMessageStore {
}
final blobs = BlobStore.instance;
final key = _storageKey(channelIndex);
// Rows (#920). The legacy-key adoption below works on blobs, so it has to
// run before this key can be considered settled: a key with no blob and no
// rows is migrated as "empty" and would then never adopt its slot-index
// history. So rows are only authoritative once they exist OR the blob is
// genuinely empty after adoption had its chance.
if (await blobs.isOnMessageRows(key)) {
final payloads = await blobs.messagePayloads(key);
if (payloads.isNotEmpty) {
return _decodePayloads(payloads, key);
}
}
// Bulk data lives in drift (#335); the fallback covers an unmigrated key
// and logs loudly if it fires.
String? jsonString = await blobs.readWithPrefsFallback(key);
@ -253,6 +319,12 @@ class ChannelMessageStore {
if (jsonString == null || jsonString.isEmpty) {
return [];
}
// The blob holds history that is not in rows yet, either because this key
// has never been migrated or because adoption above just brought legacy
// history in. Move it now so the next load and every save is on rows.
await blobs.ensureMessageRowsMigrated(key, channelHistoryToRows);
try {
final jsonList = jsonDecode(jsonString) as List<dynamic>;
return jsonList.map((json) => _messageFromJson(json)).toList();
@ -262,14 +334,34 @@ class ChannelMessageStore {
}
}
List<ChannelMessage> _decodePayloads(List<String> payloads, String key) {
final out = <ChannelMessage>[];
for (final p in payloads) {
try {
out.add(_messageFromJson(jsonDecode(p) as Map<String, dynamic>));
} catch (e) {
// One unreadable row must not cost the whole channel. Unlike the blob,
// where a bad byte took every message with it, rows fail one at a time.
appLogger.error(
'Skipping an undecodable message row in $key: $e',
tag: 'Storage',
);
}
}
return out;
}
/// Clear messages for a specific channel slot. Removes BOTH the PSK-identity
/// key and the raw slot-index key: deleteChannel needs the channel's own
/// history gone, and setChannel's reuse-clear (#193) needs any stale
/// slot-index history gone so it can't be migrated onto the new occupant.
Future<void> clearChannelMessages(int channelIndex) async {
final blobs = BlobStore.instance;
await blobs.deleteEverywhere(_storageKey(channelIndex));
await blobs.deleteEverywhere(_indexKey(channelIndex));
for (final key in {_storageKey(channelIndex), _indexKey(channelIndex)}) {
await blobs.deleteEverywhere(key);
// Rows as well, or a clear would leave the history readable (#920).
await blobs.deleteMessageRows(key);
}
}
/// Clear all channel messages
@ -277,6 +369,11 @@ class ChannelMessageStore {
final blobs = BlobStore.instance;
for (final key in await blobs.keysWithPrefix(keyFor)) {
await blobs.deleteEverywhere(key);
await blobs.deleteMessageRows(key);
}
// Row-only keys have no blob left to list, so clear by row key too.
for (final key in await blobs.messageStoreKeys()) {
if (key.startsWith(keyFor)) await blobs.deleteMessageRows(key);
}
}

@ -1,5 +1,5 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import '../models/message.dart';
import '../models/translation_support.dart';
import '../helpers/reaction_helper.dart';
@ -62,6 +62,26 @@ String? dropFromDmHistoryJson((String?, String) input) {
return jsonEncode(kept.map(MessageStore._messageToJson).toList());
}
/// Converts a whole DM-history blob into one row per message (#920).
///
/// Top-level so `compute` can send it. One row per source element, with no
/// dedupe and no sorting: the migration counts the blob independently and does
/// its own deduping, so doing either here would defeat its gate.
List<MessageRowInput> dmHistoryToRows(String blobJson) {
return (jsonDecode(blobJson) as List<dynamic>).map((e) {
final map = e as Map<String, dynamic>;
final m = MessageStore._messageFromJson(map);
return MessageRowInput(
mergeKey: MessageStore._mergeKey(m),
timestampMs: m.timestamp.millisecondsSinceEpoch,
// The source map re-encoded, not a re-serialisation of the decoded
// object: a round trip through the model would rewrite any field the
// model defaults, and this is a move, not a rewrite.
payload: jsonEncode(map),
);
}).toList();
}
class MessageStore {
static const String _keyPrefix = 'messages_';
@ -85,15 +105,34 @@ class MessageStore {
// (removeMessage).
final key = '$keyFor$contactKeyHex';
final blobs = BlobStore.instance;
// 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.
// Rows (#920): one upsert per message being saved, costing the same at
// 50,000 messages of history as at 50.
if (await blobs.ensureMessageRowsMigrated(key, dmHistoryToRows)) {
await blobs.upsertMessageRows(key, messages.map(_toRow));
return;
}
// Blob fallback for a key whose migration was refused. Off the UI isolate
// (#919): only the INCOMING messages are encoded here, and `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);
}
static MessageRowInput _toRow(Message m) => MessageRowInput(
mergeKey: _mergeKey(m),
timestampMs: m.timestamp.millisecondsSinceEpoch,
payload: jsonEncode(_messageToJson(m)),
);
/// The store's own history encoding, for tests that need a blob fixture.
/// Saves write rows now, so a test can no longer get one by saving.
@visibleForTesting
static String encodeHistoryForTest(List<Message> messages) =>
jsonEncode(messages.map(_messageToJson).toList());
static String _mergeKey(Message m) {
if (m.messageId.isNotEmpty) return 'id:${m.messageId}';
return 'x:${m.senderKeyHex}:${m.timestamp.millisecondsSinceEpoch}:${m.text}';
@ -101,17 +140,20 @@ class MessageStore {
/// Explicit delete path (#343): save merges and never removes.
///
/// Decode and re-encode run off the UI isolate (#919), as in the channel
/// store. This also gains the per-key serialisation it did not have before:
/// it was a read-modify-write outside [BlobStore.synchronized], so a save
/// landing after a delete could resurrect the deleted message.
/// On rows this is a single-row DELETE (#920). On the blob fallback the
/// decode and re-encode run off the UI isolate (#919), with the per-key
/// serialisation this path did not have before: it was a read-modify-write
/// outside [BlobStore.synchronized], so a save landing after a delete could
/// resurrect the deleted message.
Future<void> removeMessage(String contactKeyHex, Message message) async {
if (publicKeyHex.isEmpty) return;
await BlobStore.instance.mergeOffThread(
'$keyFor$contactKeyHex',
_mergeKey(message),
dropFromDmHistoryJson,
);
final key = '$keyFor$contactKeyHex';
final blobs = BlobStore.instance;
if (await blobs.ensureMessageRowsMigrated(key, dmHistoryToRows)) {
await blobs.deleteMessageRow(key, _mergeKey(message));
return;
}
await blobs.mergeOffThread(key, _mergeKey(message), dropFromDmHistoryJson);
}
Future<List<Message>> loadMessages(String contactKeyHex) async {
@ -121,9 +163,18 @@ class MessageStore {
}
final key = '$keyFor$contactKeyHex';
final oldKey = '$_keyPrefix$contactKeyHex';
final blobs = BlobStore.instance;
// Rows (#920). Only short-circuits when rows actually exist: a key marked
// migrated with no rows must still fall through to the legacy-key adoption
// below, or history stored under an older key would never be picked up.
if (await blobs.isOnMessageRows(key)) {
final payloads = await blobs.messagePayloads(key);
if (payloads.isNotEmpty) return _decodePayloads(payloads, key);
}
// Bulk data lives in drift (#335); fallback covers an unmigrated key and
// logs loudly if it fires.
final blobs = BlobStore.instance;
String? jsonString = await blobs.readWithPrefsFallback(key);
if (jsonString == null || jsonString.isEmpty) {
@ -148,6 +199,11 @@ class MessageStore {
return [];
}
// Blob history that is not in rows yet, either never migrated or just
// adopted from a legacy key. Move it so the next load and every save runs
// on rows.
await blobs.ensureMessageRowsMigrated(key, dmHistoryToRows);
try {
final jsonList = jsonDecode(jsonString) as List<dynamic>;
return jsonList.map((json) => _messageFromJson(json)).toList();
@ -156,6 +212,23 @@ class MessageStore {
}
}
List<Message> _decodePayloads(List<String> payloads, String key) {
final out = <Message>[];
for (final p in payloads) {
try {
out.add(_messageFromJson(jsonDecode(p) as Map<String, dynamic>));
} catch (e) {
// One bad row costs one message. On the blob, one bad byte cost the
// whole conversation.
appLogger.error(
'Skipping an undecodable message row in $key: $e',
tag: 'Storage',
);
}
}
return out;
}
Future<void> clearMessages(String contactKeyHex) async {
if (publicKeyHex.isEmpty) {
appLogger.warn('Public key hex is not set. Cannot clear messages.');
@ -166,6 +239,8 @@ class MessageStore {
// copy must not survive a clear and reappear via the read fallback.
await BlobStore.instance.delete(key);
await PrefsManager.instance.remove(key);
// Rows too, or a cleared conversation stays readable (#920).
await BlobStore.instance.deleteMessageRows(key);
}
static Map<String, dynamic> _messageToJson(Message msg) {

@ -51,20 +51,9 @@ void main() {
// Fixtures go through the store's own encoder rather than a hand-written map,
// which silently rots the moment a non-null field is added to the schema.
Future<String> encodeVia(List<ChannelMessage> ms) async {
final fixtureDb = OffbandDatabase(NativeDatabase.memory());
final previous = BlobStore.instance;
BlobStore.overrideForTest(BlobStore(fixtureDb));
try {
final store = ChannelMessageStore()..setPublicKeyHex = 'f' * 20;
await store.saveChannelMessages(0, ms);
final keys = await BlobStore.instance.keysWithPrefix('channel_messages_');
return (await BlobStore.instance.read(keys.single))!;
} finally {
BlobStore.overrideForTest(previous);
await fixtureDb.close();
}
}
// Saves write rows now (#920), so this calls the encoder directly.
Future<String> encodeVia(List<ChannelMessage> ms) async =>
ChannelMessageStore.encodeHistoryForTest(ms);
group('dropFromChannelHistoryJson', () {
test('drops only the target and keeps the rest', () async {

@ -43,20 +43,11 @@ void main() {
// Fixtures go through the store's OWN encoder rather than a hand-written map.
// A hand-rolled fixture silently rots the moment a non-null field is added to
// the schema, which is exactly how the first run of this test failed.
Future<String> encodeVia(List<ChannelMessage> ms) async {
final fixtureDb = OffbandDatabase(NativeDatabase.memory());
final previous = BlobStore.instance;
BlobStore.overrideForTest(BlobStore(fixtureDb));
try {
final store = ChannelMessageStore()..setPublicKeyHex = 'f' * 20;
await store.saveChannelMessages(0, ms);
final keys = await BlobStore.instance.keysWithPrefix('channel_messages_');
return (await BlobStore.instance.read(keys.single))!;
} finally {
BlobStore.overrideForTest(previous);
await fixtureDb.close();
}
}
//
// This used to get there by calling saveChannelMessages and reading the blob
// back. Saves write rows now (#920), so it calls the encoder directly.
Future<String> encodeVia(List<ChannelMessage> ms) async =>
ChannelMessageStore.encodeHistoryForTest(ms);
group('mergeChannelHistoryJson', () {
test('adds incoming messages to the stored history', () async {
@ -141,20 +132,8 @@ void main() {
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();
}
}
Future<String> encodeDmVia(List<Message> ms) async =>
MessageStore.encodeHistoryForTest(ms);
group('mergeDmHistoryJson', () {
test('adds incoming messages to the stored history', () async {

@ -0,0 +1,372 @@
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';
/// #920 B2: both stores read and write rows. These go through the public store
/// API only, because that is what the app calls and what an existing install
/// will hit on its first launch after this ships.
void main() {
late OffbandDatabase db;
late BlobStore blobs;
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
db = OffbandDatabase(NativeDatabase.memory());
blobs = BlobStore(db);
BlobStore.overrideForTest(blobs);
});
tearDown(() async {
await db.close();
BlobStore.clearTestOverride();
});
ChannelMessage chan(int i, {String? text}) => ChannelMessage(
senderName: 's',
text: text ?? 'm$i',
timestamp: DateTime.fromMillisecondsSinceEpoch(1000 + i),
isOutgoing: false,
channelIndex: 0,
messageId: 'id$i',
);
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',
);
group('channel store on rows', () {
test('a save writes rows, not a blob', () async {
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveChannelMessages(0, [chan(1), chan(2)]);
expect(await blobs.messageRowCount('channel_messages_aaaaaaaaaa0'), 2);
expect(
await blobs.read('channel_messages_aaaaaaaaaa0'),
isNull,
reason: 'the blob path is the fallback now, not the write path',
);
});
test('round-trips through load', () async {
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveChannelMessages(0, [chan(1), chan(2), chan(3)]);
final loaded = await store.loadChannelMessages(0);
expect(loaded.map((m) => m.messageId), ['id1', 'id2', 'id3']);
expect(loaded.map((m) => m.text), ['m1', 'm2', 'm3']);
});
test('a windowed save does not truncate stored history (#343)', () async {
// The in-memory list is windowed, so this is the case that made saves a
// merge in the first place. On rows it has to stay true.
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveChannelMessages(0, [chan(1), chan(2), chan(3)]);
await store.saveChannelMessages(0, [chan(4)]);
final loaded = await store.loadChannelMessages(0);
expect(loaded.map((m) => m.messageId), ['id1', 'id2', 'id3', 'id4']);
});
test('re-saving a message updates it instead of duplicating', () async {
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveChannelMessages(0, [chan(1, text: 'first')]);
await store.saveChannelMessages(0, [chan(1, text: 'edited')]);
final loaded = await store.loadChannelMessages(0);
expect(loaded.single.text, 'edited');
});
test('an existing blob history is adopted on first load', () async {
// What every current install looks like: the whole history in a blob and
// no rows at all.
const key = 'channel_messages_aaaaaaaaaa0';
await blobs.write(
key,
ChannelMessageStore.encodeHistoryForTest([chan(1), chan(2), chan(3)]),
);
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
final loaded = await store.loadChannelMessages(0);
expect(loaded.map((m) => m.messageId), ['id1', 'id2', 'id3']);
expect(await blobs.messageRowCount(key), 3, reason: 'migrated on read');
expect(await blobs.isOnMessageRows(key), isTrue);
});
test('an existing blob history is adopted on first save', () async {
const key = 'channel_messages_aaaaaaaaaa0';
await blobs.write(
key,
ChannelMessageStore.encodeHistoryForTest([chan(1), chan(2)]),
);
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveChannelMessages(0, [chan(3)]);
final loaded = await store.loadChannelMessages(0);
expect(
loaded.map((m) => m.messageId),
['id1', 'id2', 'id3'],
reason: 'the blob history must not be lost by the first row save',
);
});
test('the adopted blob is left in place', () async {
const key = 'channel_messages_aaaaaaaaaa0';
final original = ChannelMessageStore.encodeHistoryForTest([chan(1)]);
await blobs.write(key, original);
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
await store.loadChannelMessages(0);
expect(await blobs.read(key), original);
});
test('delete removes one message and keeps the rest', () async {
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveChannelMessages(0, [chan(1), chan(2), chan(3)]);
await store.removeChannelMessage(0, chan(2));
final loaded = await store.loadChannelMessages(0);
expect(loaded.map((m) => m.messageId), ['id1', 'id3']);
});
test('a deleted message is not resurrected by the next save', () async {
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveChannelMessages(0, [chan(1), chan(2)]);
await store.removeChannelMessage(0, chan(2));
// The in-memory list the app saves next may still be stale, but a save
// that re-sends the deleted message legitimately re-adds it. What must
// not happen is a save of OTHER messages bringing it back.
await store.saveChannelMessages(0, [chan(1)]);
final loaded = await store.loadChannelMessages(0);
expect(loaded.map((m) => m.messageId), ['id1']);
});
test('clear removes the rows, not just the blob', () async {
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveChannelMessages(0, [chan(1), chan(2)]);
await store.clearChannelMessages(0);
expect(await store.loadChannelMessages(0), isEmpty);
expect(await blobs.messageRowCount('channel_messages_aaaaaaaaaa0'), 0);
});
test('clearAll removes row-only histories too', () async {
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveChannelMessages(0, [chan(1)]);
await store.saveChannelMessages(1, [chan(2)]);
await store.clearAllChannelMessages();
expect(await store.loadChannelMessages(0), isEmpty);
expect(await store.loadChannelMessages(1), isEmpty);
});
test('history stays scoped per radio', () async {
// A bleed here is #472, which shipped once already.
final radioA = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
final radioB = ChannelMessageStore()..setPublicKeyHex = 'b' * 20;
await radioA.saveChannelMessages(0, [chan(1)]);
await radioB.saveChannelMessages(0, [chan(2)]);
expect((await radioA.loadChannelMessages(0)).single.messageId, 'id1');
expect((await radioB.loadChannelMessages(0)).single.messageId, 'id2');
});
test('one unreadable row costs one message, not the channel', () async {
// On the blob, a single bad byte took the whole history with it.
const key = 'channel_messages_aaaaaaaaaa0';
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveChannelMessages(0, [chan(1), chan(2)]);
await blobs.upsertMessageRows(key, const [
MessageRowInput(
mergeKey: 'id:broken',
timestampMs: 1500,
payload: '{not json',
),
]);
final loaded = await store.loadChannelMessages(0);
expect(loaded.map((m) => m.messageId), ['id1', 'id2']);
});
});
group('DM store on rows', () {
test('a save writes rows, not a blob', () async {
final store = MessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveMessages('beef', [dm(1), dm(2)]);
expect(await blobs.messageRowCount('messages_aaaaaaaaaabeef'), 2);
expect(await blobs.read('messages_aaaaaaaaaabeef'), isNull);
});
test('round-trips through load', () async {
final store = MessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveMessages('beef', [dm(1), dm(2)]);
final loaded = await store.loadMessages('beef');
expect(loaded.map((m) => m.messageId), ['id1', 'id2']);
});
test('a windowed save does not truncate stored history (#343)', () async {
final store = MessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveMessages('beef', [dm(1), dm(2)]);
await store.saveMessages('beef', [dm(3)]);
expect((await store.loadMessages('beef')).map((m) => m.messageId), [
'id1',
'id2',
'id3',
]);
});
test('an existing blob history is adopted on first load', () async {
const key = 'messages_aaaaaaaaaabeef';
await blobs.write(key, MessageStore.encodeHistoryForTest([dm(1), dm(2)]));
final store = MessageStore()..setPublicKeyHex = 'a' * 20;
final loaded = await store.loadMessages('beef');
expect(loaded.map((m) => m.messageId), ['id1', 'id2']);
expect(await blobs.messageRowCount(key), 2);
});
test('an existing blob history is adopted on first save', () async {
const key = 'messages_aaaaaaaaaabeef';
await blobs.write(key, MessageStore.encodeHistoryForTest([dm(1)]));
final store = MessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveMessages('beef', [dm(2)]);
expect((await store.loadMessages('beef')).map((m) => m.messageId), [
'id1',
'id2',
]);
});
test('delete removes one message', () async {
final store = MessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveMessages('beef', [dm(1), dm(2), dm(3)]);
await store.removeMessage('beef', dm(2));
expect((await store.loadMessages('beef')).map((m) => m.messageId), [
'id1',
'id3',
]);
});
test('clear removes the rows', () async {
final store = MessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveMessages('beef', [dm(1)]);
await store.clearMessages('beef');
expect(await store.loadMessages('beef'), isEmpty);
});
test('conversations stay scoped per contact and per radio', () async {
final radioA = MessageStore()..setPublicKeyHex = 'a' * 20;
final radioB = MessageStore()..setPublicKeyHex = 'b' * 20;
await radioA.saveMessages('beef', [dm(1)]);
await radioA.saveMessages('cafe', [dm(2)]);
await radioB.saveMessages('beef', [dm(3)]);
expect((await radioA.loadMessages('beef')).single.messageId, 'id1');
expect((await radioA.loadMessages('cafe')).single.messageId, 'id2');
expect((await radioB.loadMessages('beef')).single.messageId, 'id3');
});
});
group('refused migration keeps the store working on the blob', () {
test('channel: a corrupt blob still reads and saves', () async {
const key = 'channel_messages_aaaaaaaaaa0';
// Valid JSON that the converter cannot turn into messages: the record
// decode throws, so the migration must refuse and the blob path stays.
await blobs.write(key, '[{"not":"a message"}]');
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
final loaded = await store.loadChannelMessages(0);
expect(
await blobs.isOnMessageRows(key),
isFalse,
reason: 'a converter that throws must not mark the key migrated',
);
expect(loaded, isEmpty, reason: 'the blob itself does not decode either');
expect(await blobs.read(key), '[{"not":"a message"}]');
// And a save still lands, on the blob path.
await store.saveChannelMessages(0, [chan(1)]);
expect(await blobs.read(key), isNotNull);
});
test(
'channel: the blob fallback still merges rather than overwriting',
() async {
const key = 'channel_messages_aaaaaaaaaa0';
await blobs.write(key, '[{"not":"a message"}]');
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
await store.loadChannelMessages(0);
// mergeOffThread fails closed on an undecodable blob, so the refused
// key keeps its bytes rather than being replaced by the incoming save.
await store.saveChannelMessages(0, [chan(1)]);
expect(await blobs.read(key), '[{"not":"a message"}]');
expect(
await blobs.messageRowCount(key),
0,
reason: 'a refused key must not accumulate half a history in rows',
);
},
);
});
test('the payload a row stores is the stores own encoding', () async {
// Guards the migration contract: rows hold exactly what the blob held, so
// a payload is decodable by the same _messageFromJson.
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveChannelMessages(0, [chan(1)]);
final payload = (await blobs.messagePayloads(
'channel_messages_aaaaaaaaaa0',
)).single;
final decoded = jsonDecode(payload) as Map<String, dynamic>;
expect(decoded['messageId'], 'id1');
expect(decoded['text'], 'm1');
expect(decoded.containsKey('status'), isTrue);
});
}
Loading…
Cancel
Save

Powered by TurnKey Linux.