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
diffwireauto 1 month ago
parent 6ac4f915ef
commit fec5c95fd7

@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:convert';
import 'package:drift/drift.dart';
import 'package:flutter/foundation.dart';
import '../../utils/app_logger.dart';
@ -138,6 +139,110 @@ class BlobStore {
await (_db.delete(_db.storedBlobs)..where((t) => t.key.equals(key))).go();
}
// ---------------------------------------------------------------------------
// Per-message rows (#920)
//
// The blob API above keeps a whole history in one row, so every save paid for
// every message that came before it. These methods work one message at a
// time. They live on BlobStore rather than in a second class because both
// APIs must use the SAME OffbandDatabase instance: opening the database twice
// is an error on the web backends, and a second singleton would be one
// mistake away from doing exactly that.
// ---------------------------------------------------------------------------
/// Inserts or updates [rows] under [storeKey] in one transaction.
///
/// Upserts on `(storeKey, mergeKey)`, which is the same identity the blob
/// merge deduped on, so saving a message that is already stored updates it
/// instead of duplicating it. Cost is proportional to [rows], not to the
/// history already stored, which is the entire point.
Future<void> upsertMessageRows(
String storeKey,
Iterable<MessageRowInput> rows,
) async {
if (rows.isEmpty) return;
await _db.batch((b) {
b.insertAllOnConflictUpdate(
_db.messageRecords,
rows
.map(
(r) => MessageRecordsCompanion.insert(
storeKey: storeKey,
mergeKey: r.mergeKey,
timestampMs: r.timestampMs,
payload: r.payload,
),
)
.toList(),
);
});
}
/// The stored message payloads for [storeKey], oldest first.
///
/// Ordering and paging happen in SQLite, so loading the most recent N no
/// longer means decoding the whole history first. [limit] with no [offset]
/// returns the NEWEST [limit] messages, still in oldest-first order, because
/// that is what a chat screen opens with.
Future<List<String>> messagePayloads(
String storeKey, {
int? limit,
int? offset,
}) async {
final q = _db.select(_db.messageRecords)
..where((t) => t.storeKey.equals(storeKey));
if (limit != null) {
q.orderBy([
(t) => OrderingTerm(expression: t.timestampMs, mode: OrderingMode.desc),
]);
q.limit(limit, offset: offset);
final newestFirst = await q.get();
return newestFirst.reversed.map((r) => r.payload).toList();
}
q.orderBy([(t) => OrderingTerm(expression: t.timestampMs)]);
final rows = await q.get();
return rows.map((r) => r.payload).toList();
}
/// How many messages are stored under [storeKey]. The migration's readback
/// gate compares this against the number of records decoded from the blob.
Future<int> messageRowCount(String storeKey) async {
final count = _db.messageRecords.mergeKey.count();
final row =
await (_db.selectOnly(_db.messageRecords)
..addColumns([count])
..where(_db.messageRecords.storeKey.equals(storeKey)))
.getSingle();
return row.read(count) ?? 0;
}
/// Removes one message. O(1), with no history rewrite.
Future<void> deleteMessageRow(String storeKey, String mergeKey) async {
await (_db.delete(_db.messageRecords)..where(
(t) => t.storeKey.equals(storeKey) & t.mergeKey.equals(mergeKey),
))
.go();
}
/// Removes every message under [storeKey], for the stores' clear paths.
Future<void> deleteMessageRows(String storeKey) async {
await (_db.delete(
_db.messageRecords,
)..where((t) => t.storeKey.equals(storeKey))).go();
}
/// Store keys that already have rows, so a caller can tell a migrated key
/// from one still on the blob path without reading any payloads.
Future<Set<String>> messageStoreKeys() async {
final key = _db.messageRecords.storeKey;
final rows =
await (_db.selectOnly(_db.messageRecords)
..addColumns([key])
..groupBy([key]))
.get();
return rows.map((r) => r.read(key)!).toSet();
}
/// Read-modify-write for a bulk key with the decode, merge and re-encode run
/// **off the UI isolate** (#919).
///
@ -412,6 +517,23 @@ class BlobStore {
}
}
/// One message on its way into [MessageRecords] (#920).
///
/// A plain record rather than a drift companion so the stores can build it
/// without importing the generated code, and so the merge key and timestamp
/// are named at the call site instead of being positional.
class MessageRowInput {
const MessageRowInput({
required this.mergeKey,
required this.timestampMs,
required this.payload,
});
final String mergeKey;
final int timestampMs;
final String payload;
}
/// Merge step for [BlobStore.mergeOffThread], run on another isolate.
///
/// Takes `(storedJson, payload)` and returns the JSON to store, or null to

@ -28,7 +28,7 @@ part 'offband_database.g.dart';
/// IndexedDB and runs in a worker rather than on the UI thread.
///
/// Settings stay in SharedPreferences. Only bulk data moves here.
@DriftDatabase(tables: [StoredBlobs])
@DriftDatabase(tables: [StoredBlobs, MessageRecords])
class OffbandDatabase extends _$OffbandDatabase {
OffbandDatabase([QueryExecutor? executor])
: super(executor ?? _defaultExecutor());
@ -315,7 +315,41 @@ class OffbandDatabase extends _$OffbandDatabase {
}
@override
int get schemaVersion => 1;
int get schemaVersion => 2;
/// Schema 2 adds [MessageRecords] (#920). Purely additive: [StoredBlobs] is
/// untouched and keeps every byte it had, so an install that opens this
/// schema and is then taken back to an older build still finds its history
/// where that build looks for it.
@override
MigrationStrategy get migration => MigrationStrategy(
onUpgrade: (m, from, to) async {
if (from < 2) {
await m.createTable(messageRecords);
await m.createIndex(
Index(
'idx_message_records_store_ts',
'CREATE INDEX IF NOT EXISTS idx_message_records_store_ts '
'ON message_records (store_key, timestamp_ms)',
),
);
appLogger.info(
'drift schema $from -> $to: created message_records (#920). '
'stored_blobs untouched.',
);
}
},
beforeOpen: (details) async {
// A fresh database is created at the current schema, so onUpgrade never
// runs for it and the index would be missing.
if (details.wasCreated) {
await customStatement(
'CREATE INDEX IF NOT EXISTS idx_message_records_store_ts '
'ON message_records (store_key, timestamp_ms)',
);
}
},
);
/// Step-1 gate for #335: proves the database opens, writes and reads back on
/// the current platform. Deliberately trivial - no user data is involved, so
@ -352,3 +386,46 @@ class StoredBlobs extends Table {
@override
Set<Column> get primaryKey => {key};
}
/// One row per message, replacing one element of a [StoredBlobs] JSON array
/// each (#920).
///
/// Why this exists: with the whole history in one blob, saving a single message
/// decoded, rebuilt and re-encoded every message that came before it. On the
/// owner's largest channel that was 9,230 records and 134 ms of work per
/// arriving message, and #919 could only move that cost to another isolate,
/// not remove it. One row per message makes a save an upsert of one row.
///
/// [storeKey] is deliberately the SAME key the blob used, not a new scheme.
/// All of the per-radio and per-channel scoping rules (#194, #472) already live
/// in those keys, so reusing them means this table inherits that scoping
/// unchanged, and the migration becomes a per-key operation with an exact
/// record count to verify against.
///
/// [payload] holds the per-message JSON exactly as the stores already emit it,
/// rather than a column per field. That keeps the migration a pure re-key with
/// no field mapping that could silently drop or coerce a value, lets the
/// stores reuse their existing encoders, and means a new message field needs
/// no second data migration. The trade: message fields are not SQL-queryable.
/// Columns can be added beside the payload later without another migration if
/// that is ever wanted.
class MessageRecords extends Table {
@override
String get tableName => 'message_records';
/// The store key this message belongs to, byte-identical to the blob key.
TextColumn get storeKey => text()();
/// Stable per-message identity: the stores' existing `_mergeKey`. Upserting
/// on it preserves exactly the dedupe semantics the blob merge had.
TextColumn get mergeKey => text()();
/// Sender-claimed time in epoch milliseconds, for ordering and paging. An
/// INTEGER column so ORDER BY and LIMIT happen in SQLite, not in Dart.
IntColumn get timestampMs => integer()();
TextColumn get payload => text()();
@override
Set<Column> get primaryKey => {storeKey, mergeKey};
}

@ -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…
Cancel
Save

Powered by TurnKey Linux.