task(#920): B1 message_records table and the per-message row API
Schema 2 adds one row per message beside StoredBlobs, which stays exactly as it is. A save becomes an upsert of one row, so its cost stops depending on how much history is already stored. That is what #919 could not do: it moved the whole-history re-encode to another isolate, it did not remove it. Shape, and why it is this shape: store_key the EXISTING blob key, byte-identical merge_key the stores' existing _mergeKey identity timestamp_ms INTEGER, so ORDER BY and LIMIT run in SQLite payload the per-message JSON the stores already emit PK (store_key, merge_key), index (store_key, timestamp_ms) Reusing the blob key means every per-radio and per-channel scoping rule (#194, #472) carries over untouched, and the migration becomes a per-key operation with an exact record count to verify against. The payload is JSON rather than a column per field. A Message has 25 fields including three maps, two byte arrays and the translation set; hand-mapping them would mean trusting a new field-by-field converter against 41 MB of real history on its first run, and #355 cost 574 messages the last time a storage migration was hurried. With a payload column the migration is a pure re-key, the stores' existing encoders are reused verbatim, and a new message field needs no second migration. The trade is that message fields are not SQL-queryable; nothing asks for that today, and columns can be added beside the payload later without another data migration. Flagged for the owner on the issue before building it. The row API lives on BlobStore rather than in a second class because both APIs must share one OffbandDatabase: opening it twice is an error on the web backends, and a second singleton would be one mistake away from doing that. `limit` with no `offset` returns the NEWEST n, still oldest-first, because that is what a chat screen opens with. Tests: 18. The row set covers store-key scoping (a leak there would be a history bleed between radios), merge-key upsert, paging, per-row delete, and rows coexisting with a retained blob. The schema set builds a database that looks like one an older build left behind, v1 table with real data and user_version 1, and proves the upgrade runs, creates a usable table, leaves the blobs byte-identical and lands the index on both an upgraded and a fresh database. Citadel: meshcore-open-g6j Refs #920, #917, #334 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>feat/920-message-rows
parent
6ac4f915ef
commit
fec5c95fd7
@ -0,0 +1,129 @@
|
||||
import 'package:drift/drift.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter_test/flutter_test.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';
|
||||
|
||||
/// #920: schema 1 -> 2 adds `message_records` and must not touch a single byte
|
||||
/// of `stored_blobs`. Every existing install is on schema 1 with its whole
|
||||
/// history in there, so this is the test that stands between a schema bump and
|
||||
/// 41 MB of someone's messages.
|
||||
void main() {
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
});
|
||||
|
||||
tearDown(BlobStore.clearTestOverride);
|
||||
|
||||
/// A database that looks exactly like one an older build left behind: the v1
|
||||
/// table, real data in it, and `user_version` still 1 so drift runs the
|
||||
/// upgrade rather than creating everything fresh.
|
||||
QueryExecutor v1DatabaseWith(Map<String, String> blobs) {
|
||||
return NativeDatabase.memory(
|
||||
setup: (raw) {
|
||||
raw.execute(
|
||||
'CREATE TABLE stored_blobs ('
|
||||
'key TEXT NOT NULL, '
|
||||
'value TEXT NOT NULL, '
|
||||
"updated_at INTEGER NOT NULL DEFAULT (CAST(strftime('%s', "
|
||||
"CURRENT_TIMESTAMP) AS INTEGER)), "
|
||||
'PRIMARY KEY (key))',
|
||||
);
|
||||
for (final entry in blobs.entries) {
|
||||
final escaped = entry.value.replaceAll("'", "''");
|
||||
raw.execute(
|
||||
"INSERT INTO stored_blobs (key, value) VALUES ('${entry.key}', "
|
||||
"'$escaped')",
|
||||
);
|
||||
}
|
||||
raw.execute('PRAGMA user_version = 1');
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test('upgrading from 1 to 2 keeps every blob byte-identical', () async {
|
||||
const history = '[{"messageId":"id1","text":"don\'t lose me"}]';
|
||||
final db = OffbandDatabase(
|
||||
v1DatabaseWith({
|
||||
'channel_messages_abc0123456psk_dead': history,
|
||||
'contacts': '[{"name":"someone"}]',
|
||||
}),
|
||||
);
|
||||
final blobs = BlobStore(db);
|
||||
|
||||
// Opening is lazy; the first query is what triggers the migration.
|
||||
expect(await blobs.read('channel_messages_abc0123456psk_dead'), history);
|
||||
expect(await blobs.read('contacts'), '[{"name":"someone"}]');
|
||||
|
||||
await db.close();
|
||||
});
|
||||
|
||||
test('upgrading from 1 to 2 creates a usable message_records', () async {
|
||||
final db = OffbandDatabase(v1DatabaseWith({'contacts': '[]'}));
|
||||
final blobs = BlobStore(db);
|
||||
|
||||
await blobs.upsertMessageRows('k', const [
|
||||
MessageRowInput(mergeKey: 'id:a', timestampMs: 1, payload: '{"a":1}'),
|
||||
]);
|
||||
|
||||
expect(await blobs.messagePayloads('k'), ['{"a":1}']);
|
||||
await db.close();
|
||||
});
|
||||
|
||||
test('the upgraded database reports schema 2', () async {
|
||||
final db = OffbandDatabase(v1DatabaseWith({'contacts': '[]'}));
|
||||
|
||||
// Forces the open, and therefore the migration.
|
||||
await BlobStore(db).read('contacts');
|
||||
final version = await db
|
||||
.customSelect('PRAGMA user_version')
|
||||
.getSingle()
|
||||
.then((r) => r.data.values.first as int);
|
||||
|
||||
expect(version, 2);
|
||||
await db.close();
|
||||
});
|
||||
|
||||
test('the store-key index exists after an upgrade', () async {
|
||||
final db = OffbandDatabase(v1DatabaseWith({'contacts': '[]'}));
|
||||
await BlobStore(db).read('contacts');
|
||||
|
||||
final names = await db
|
||||
.customSelect(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'index' "
|
||||
"AND tbl_name = 'message_records'",
|
||||
)
|
||||
.get();
|
||||
|
||||
expect(
|
||||
names.map((r) => r.data['name']),
|
||||
contains('idx_message_records_store_ts'),
|
||||
reason: 'without it, ORDER BY timestamp_ms scans the whole table',
|
||||
);
|
||||
await db.close();
|
||||
});
|
||||
|
||||
test('a database created fresh at schema 2 also gets the index', () async {
|
||||
// onUpgrade does not run for a new database, so the index has to be
|
||||
// created in beforeOpen as well or a fresh install silently loses it.
|
||||
final db = OffbandDatabase(NativeDatabase.memory());
|
||||
await BlobStore(db).read('anything');
|
||||
|
||||
final names = await db
|
||||
.customSelect(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'index' "
|
||||
"AND tbl_name = 'message_records'",
|
||||
)
|
||||
.get();
|
||||
|
||||
expect(
|
||||
names.map((r) => r.data['name']),
|
||||
contains('idx_message_records_store_ts'),
|
||||
);
|
||||
await db.close();
|
||||
});
|
||||
}
|
||||
@ -0,0 +1,173 @@
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter_test/flutter_test.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';
|
||||
|
||||
/// #920 B1: one row per message. These pin the properties the stores and the
|
||||
/// migration are about to rely on, in particular that an upsert is scoped to
|
||||
/// its store key and deduped by merge key exactly as the blob merge was.
|
||||
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();
|
||||
});
|
||||
|
||||
MessageRowInput row(int i, {String? text, String? id}) => MessageRowInput(
|
||||
mergeKey: 'id:${id ?? 'id$i'}',
|
||||
timestampMs: 1000 + i,
|
||||
payload: '{"messageId":"${id ?? 'id$i'}","text":"${text ?? 'm$i'}"}',
|
||||
);
|
||||
|
||||
test('stores and reads back in timestamp order', () async {
|
||||
// Inserted out of order on purpose: ordering must come from SQLite, not
|
||||
// from insertion sequence.
|
||||
await blobs.upsertMessageRows('k', [row(9), row(2), row(5)]);
|
||||
|
||||
final out = await blobs.messagePayloads('k');
|
||||
|
||||
expect(out, [
|
||||
'{"messageId":"id2","text":"m2"}',
|
||||
'{"messageId":"id5","text":"m5"}',
|
||||
'{"messageId":"id9","text":"m9"}',
|
||||
]);
|
||||
});
|
||||
|
||||
test('upsert on the same merge key updates, never duplicates', () async {
|
||||
await blobs.upsertMessageRows('k', [row(1, text: 'original')]);
|
||||
await blobs.upsertMessageRows('k', [row(1, text: 'edited')]);
|
||||
|
||||
expect(await blobs.messageRowCount('k'), 1);
|
||||
expect(await blobs.messagePayloads('k'), [
|
||||
'{"messageId":"id1","text":"edited"}',
|
||||
]);
|
||||
});
|
||||
|
||||
test('rows are scoped to their store key', () async {
|
||||
// The key carries all the per-radio and per-channel scoping (#194, #472),
|
||||
// so a leak across keys here would be a history bleed between radios.
|
||||
await blobs.upsertMessageRows('radio_a', [row(1), row(2)]);
|
||||
await blobs.upsertMessageRows('radio_b', [row(1)]);
|
||||
|
||||
expect(await blobs.messageRowCount('radio_a'), 2);
|
||||
expect(await blobs.messageRowCount('radio_b'), 1);
|
||||
expect(await blobs.messagePayloads('radio_b'), [
|
||||
'{"messageId":"id1","text":"m1"}',
|
||||
]);
|
||||
});
|
||||
|
||||
test('the same merge key under two store keys is two messages', () async {
|
||||
await blobs.upsertMessageRows('a', [row(1, text: 'in a')]);
|
||||
await blobs.upsertMessageRows('b', [row(1, text: 'in b')]);
|
||||
|
||||
expect(await blobs.messagePayloads('a'), [
|
||||
'{"messageId":"id1","text":"in a"}',
|
||||
]);
|
||||
expect(await blobs.messagePayloads('b'), [
|
||||
'{"messageId":"id1","text":"in b"}',
|
||||
]);
|
||||
});
|
||||
|
||||
test('limit returns the NEWEST n, still oldest-first', () async {
|
||||
await blobs.upsertMessageRows('k', [for (var i = 1; i <= 10; i++) row(i)]);
|
||||
|
||||
final out = await blobs.messagePayloads('k', limit: 3);
|
||||
|
||||
expect(out, [
|
||||
'{"messageId":"id8","text":"m8"}',
|
||||
'{"messageId":"id9","text":"m9"}',
|
||||
'{"messageId":"id10","text":"m10"}',
|
||||
]);
|
||||
});
|
||||
|
||||
test('limit with offset pages backwards through history', () async {
|
||||
await blobs.upsertMessageRows('k', [for (var i = 1; i <= 10; i++) row(i)]);
|
||||
|
||||
final page2 = await blobs.messagePayloads('k', limit: 3, offset: 3);
|
||||
|
||||
expect(page2, [
|
||||
'{"messageId":"id5","text":"m5"}',
|
||||
'{"messageId":"id6","text":"m6"}',
|
||||
'{"messageId":"id7","text":"m7"}',
|
||||
]);
|
||||
});
|
||||
|
||||
test('deleting one row leaves the rest alone', () async {
|
||||
await blobs.upsertMessageRows('k', [row(1), row(2), row(3)]);
|
||||
|
||||
await blobs.deleteMessageRow('k', 'id:id2');
|
||||
|
||||
expect(await blobs.messagePayloads('k'), [
|
||||
'{"messageId":"id1","text":"m1"}',
|
||||
'{"messageId":"id3","text":"m3"}',
|
||||
]);
|
||||
});
|
||||
|
||||
test('deleting one row does not touch another store key', () async {
|
||||
await blobs.upsertMessageRows('a', [row(1)]);
|
||||
await blobs.upsertMessageRows('b', [row(1)]);
|
||||
|
||||
await blobs.deleteMessageRow('a', 'id:id1');
|
||||
|
||||
expect(await blobs.messageRowCount('a'), 0);
|
||||
expect(await blobs.messageRowCount('b'), 1);
|
||||
});
|
||||
|
||||
test('clearing a key removes only that key', () async {
|
||||
await blobs.upsertMessageRows('a', [row(1), row(2)]);
|
||||
await blobs.upsertMessageRows('b', [row(1)]);
|
||||
|
||||
await blobs.deleteMessageRows('a');
|
||||
|
||||
expect(await blobs.messageRowCount('a'), 0);
|
||||
expect(await blobs.messageRowCount('b'), 1);
|
||||
});
|
||||
|
||||
test('messageStoreKeys lists keys that have rows, deduped', () async {
|
||||
await blobs.upsertMessageRows('a', [row(1), row(2)]);
|
||||
await blobs.upsertMessageRows('b', [row(1)]);
|
||||
|
||||
expect(await blobs.messageStoreKeys(), {'a', 'b'});
|
||||
});
|
||||
|
||||
test('an empty upsert is a no-op, not an error', () async {
|
||||
await blobs.upsertMessageRows('k', const []);
|
||||
|
||||
expect(await blobs.messageRowCount('k'), 0);
|
||||
});
|
||||
|
||||
test('count and payloads are empty for an unknown key', () async {
|
||||
expect(await blobs.messageRowCount('never-seen'), 0);
|
||||
expect(await blobs.messagePayloads('never-seen'), isEmpty);
|
||||
});
|
||||
|
||||
test('message rows and the blob for the same key coexist', () async {
|
||||
// The migration is additive: during and after it, the blob is still there
|
||||
// and must not be disturbed by anything on the row path (#920).
|
||||
await blobs.write('k', '[{"messageId":"old"}]');
|
||||
await blobs.upsertMessageRows('k', [row(1)]);
|
||||
|
||||
expect(await blobs.read('k'), '[{"messageId":"old"}]');
|
||||
expect(await blobs.messageRowCount('k'), 1);
|
||||
|
||||
await blobs.deleteMessageRows('k');
|
||||
expect(
|
||||
await blobs.read('k'),
|
||||
'[{"messageId":"old"}]',
|
||||
reason: 'clearing rows must never touch the retained blob',
|
||||
);
|
||||
});
|
||||
}
|
||||
Loading…
Reference in new issue