feat: read marks, mute and the notification ledger, schema 46 to 47 (notifications, Phase 3)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-22 12:08:33 +02:00
1 parent 1ac519059f
commit c248ab529c
10 files changed
+7324 -4

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -26,6 +26,8 @@ import mobi.giza.compose.database.dao.GiftWrapSealDao
import mobi.giza.compose.database.dao.GroupKeyStateDao
import mobi.giza.compose.database.dao.GroupSignedEventDao
import mobi.giza.compose.database.dao.GroupInboxDao
import mobi.giza.compose.database.dao.NotificationDao
import mobi.giza.compose.database.migrations.ReadMarkMigrationSpec
import mobi.giza.compose.database.dao.InboxKeyDao
import mobi.giza.compose.database.dao.InReplyToRelationDao
import mobi.giza.compose.database.dao.KeyShareDao
@@ -108,6 +110,7 @@ import mobi.giza.compose.database.model.NegentropySynchronizeRequest
import mobi.giza.compose.database.model.NegentropySynchronizeResult
import mobi.giza.compose.database.model.NostrEvent
import mobi.giza.compose.database.model.NostrEventRelay
import mobi.giza.compose.database.model.NotificationLedger
import mobi.giza.compose.database.model.Participant
import mobi.giza.compose.database.model.Post
import mobi.giza.compose.database.model.Profile
@@ -196,6 +199,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
NegentropySynchronizeResult::class,
NostrEvent::class,
NostrEventRelay::class,
NotificationLedger::class,
Participant::class,
Post::class,
Profile::class,
@@ -209,7 +213,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
UnsignedNostrEvent::class,
Zap::class
],
version = 46,
version = 47,
autoMigrations = [
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
// generate the migration itself — nothing existing changes shape.
@@ -489,6 +493,11 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
// can find a threshold-1 key, and GroupInboxWrap, GroupInboxMessage and
// GroupInboxPublication, and InboxSigning (Phase 5). New tables only, so Room generates it.
AutoMigration(from = 45, to = 46),
// v47 adds notifications' storage (docs/notifications-and-background-sync.md, Phase 3):
// ChatRoom.lastReadMessageId, ChatRoom.notifications and the NotificationLedger table.
// Room generates the shape; ReadMarkMigrationSpec then marks every existing room read up
// to its newest line, so an upgrade does not turn the user's whole history unread.
AutoMigration(from = 46, to = 47, spec = ReadMarkMigrationSpec::class),
]
)
@ConstructedBy(GizaDatabaseConstructor::class)
@@ -538,6 +547,8 @@ abstract class GizaDatabase: RoomDatabase() {
abstract fun groupInboxDao(): GroupInboxDao
abstract fun notificationDao(): NotificationDao
abstract fun connectionDao(): ConnectionDao
@@ -0,0 +1,154 @@
package mobi.giza.compose.database.dao
import androidx.room3.Dao
import androidx.room3.Insert
import androidx.room3.OnConflictStrategy
import androidx.room3.Query
import androidx.room3.Transaction
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlin.time.Instant
import kotlinx.coroutines.flow.Flow
import mobi.giza.compose.database.model.ChatMessage
import mobi.giza.compose.database.model.NotificationLedger
/**
* Read marks, the notification cursor and the background sync's record.
* docs/notifications-and-background-sync.md, Phase 3.
*
* Every mark here only moves forward. A read mark moved back would raise an unread count the
* user already cleared; a cursor moved back would post again what was already posted.
*/
@Dao
abstract class NotificationDao {
// -- read marks (D8) ---------------------------------------------------------------------
/** Marks [chatRoomId] read up to [upTo], unless it is already read further. */
@Query(
"UPDATE ChatRoom SET lastReadMessageId = :upTo " +
"WHERE id = :chatRoomId AND (lastReadMessageId IS NULL OR lastReadMessageId < :upTo)"
)
abstract suspend fun markRead(chatRoomId: String, upTo: Long): Int
/** Marks [chatRoomId] read up to its newest line. */
@Query(
"UPDATE ChatRoom SET lastReadMessageId = (SELECT MAX(id) FROM ChatMessage WHERE chatRoomId = ChatRoom.id) " +
"WHERE id = :chatRoomId AND EXISTS (SELECT 1 FROM ChatMessage WHERE chatRoomId = ChatRoom.id " +
"AND (ChatRoom.lastReadMessageId IS NULL OR id > ChatRoom.lastReadMessageId))"
)
abstract suspend fun markAllRead(chatRoomId: String): Int
/** The newest line in [chatRoomId], read or not. */
@Query("SELECT MAX(id) FROM ChatMessage WHERE chatRoomId = :chatRoomId")
abstract suspend fun newestMessageId(chatRoomId: String): Long?
/**
* Lines in [chatRoomId] the user has not been shown: said by somebody else, above the read
* mark, and in [kinds] -- the conversation, not the transcript of ceremonies around it.
*/
@Query(
"SELECT COUNT(*) FROM ChatMessage JOIN ChatRoom ON ChatRoom.id = ChatMessage.chatRoomId " +
"WHERE ChatMessage.chatRoomId = :chatRoomId AND ChatMessage.isUserMessage = 0 " +
"AND ChatMessage.deletedAt IS NULL AND ChatMessage.messageType IN (:kinds) " +
"AND ChatMessage.id > COALESCE(ChatRoom.lastReadMessageId, 0)"
)
abstract suspend fun unreadCount(chatRoomId: String, kinds: List<String> = UNREAD_KINDS): Int
/** Unread lines per room, for every room [userPublicKey] is in and has not left or deleted. */
@Query(
"SELECT ChatMessage.chatRoomId AS chatRoomId, COUNT(*) AS unread FROM ChatMessage " +
"JOIN ChatRoom ON ChatRoom.id = ChatMessage.chatRoomId " +
"WHERE ChatRoom.userPublicKey = :userPublicKey AND ChatRoom.deletedAt IS NULL " +
"AND ChatRoom.leftGroupAt IS NULL AND ChatMessage.isUserMessage = 0 " +
"AND ChatMessage.deletedAt IS NULL AND ChatMessage.messageType IN (:kinds) " +
"AND ChatMessage.id > COALESCE(ChatRoom.lastReadMessageId, 0) " +
"GROUP BY ChatMessage.chatRoomId"
)
abstract fun observeUnreadCounts(userPublicKey: HexKey, kinds: List<String> = UNREAD_KINDS): Flow<List<RoomUnread>>
@Query("UPDATE ChatRoom SET notifications = :notifications WHERE id = :chatRoomId")
abstract suspend fun setNotifications(chatRoomId: String, notifications: String)
// -- the cursor (D2, D3) -----------------------------------------------------------------
@Query("SELECT * FROM NotificationLedger WHERE userPublicKey = :userPublicKey")
abstract suspend fun getLedger(userPublicKey: HexKey): NotificationLedger?
@Query("SELECT * FROM NotificationLedger WHERE userPublicKey = :userPublicKey")
abstract fun observeLedger(userPublicKey: HexKey): Flow<NotificationLedger?>
@Insert(onConflict = OnConflictStrategy.IGNORE)
protected abstract suspend fun insertLedger(ledger: NotificationLedger): Long
@Query(
"SELECT MAX(ChatMessage.id) FROM ChatMessage JOIN ChatRoom ON ChatRoom.id = ChatMessage.chatRoomId " +
"WHERE ChatRoom.userPublicKey = :userPublicKey"
)
protected abstract suspend fun newestMessageIdFor(userPublicKey: HexKey): Long?
@Query(
"UPDATE ChatRoom SET lastReadMessageId = (SELECT MAX(id) FROM ChatMessage WHERE chatRoomId = ChatRoom.id) " +
"WHERE userPublicKey = :userPublicKey"
)
protected abstract suspend fun markEverythingReadFor(userPublicKey: HexKey)
/**
* Starts notifying for [userPublicKey], once: the cursor at the newest line it holds, and every
* room read up to its newest line -- what a device had when it started counting is not news.
* Returns false, and changes nothing, when it was already armed.
*/
@Transaction
open suspend fun arm(userPublicKey: HexKey, at: Instant): Boolean {
if (getLedger(userPublicKey) != null) return false
markEverythingReadFor(userPublicKey)
insertLedger(
NotificationLedger(
userPublicKey = userPublicKey,
armedAt = at,
cursorMessageId = newestMessageIdFor(userPublicKey) ?: 0,
)
)
return true
}
/** Moves the cursor to [cursorMessageId], unless it is already past it. */
@Query(
"UPDATE NotificationLedger SET cursorMessageId = :cursorMessageId " +
"WHERE userPublicKey = :userPublicKey AND cursorMessageId < :cursorMessageId"
)
abstract suspend fun advanceCursor(userPublicKey: HexKey, cursorMessageId: Long): Int
/**
* Lines above [cursor] in [userPublicKey]'s rooms that somebody else wrote, oldest first, at most
* [limit] of them. The dispatcher decides about these and moves the cursor past them.
*/
@Query(
"SELECT ChatMessage.* FROM ChatMessage JOIN ChatRoom ON ChatRoom.id = ChatMessage.chatRoomId " +
"WHERE ChatRoom.userPublicKey = :userPublicKey AND ChatMessage.id > :cursor " +
"ORDER BY ChatMessage.id ASC LIMIT :limit"
)
abstract fun observeAfter(userPublicKey: HexKey, cursor: Long, limit: Int = 200): Flow<List<ChatMessage>>
@Query(
"SELECT ChatMessage.* FROM ChatMessage JOIN ChatRoom ON ChatRoom.id = ChatMessage.chatRoomId " +
"WHERE ChatRoom.userPublicKey = :userPublicKey AND ChatMessage.id > :cursor " +
"ORDER BY ChatMessage.id ASC LIMIT :limit"
)
abstract suspend fun getAfter(userPublicKey: HexKey, cursor: Long, limit: Int = 200): List<ChatMessage>
// -- the background sync's record (D5) ---------------------------------------------------
@Query(
"UPDATE NotificationLedger SET lastBackgroundSyncAt = :at, lastBackgroundSyncOutcome = :outcome, " +
"lastBackgroundSyncKind = :kind WHERE userPublicKey = :userPublicKey"
)
abstract suspend fun recordBackgroundSync(userPublicKey: HexKey, at: Instant, outcome: String, kind: String): Int
companion object {
/** What an unread count counts: the conversation. */
val UNREAD_KINDS = listOf(ChatMessage.TYPE_MESSAGE, ChatMessage.TYPE_DIRECT_MESSAGE)
}
}
/** One room's unread count. */
data class RoomUnread(val chatRoomId: String, val unread: Int)
@@ -0,0 +1,24 @@
package mobi.giza.compose.database.migrations
import androidx.room3.migration.AutoMigrationSpec
import androidx.sqlite.SQLiteConnection
import androidx.sqlite.execSQL
/**
* v47's data half: every room an upgraded install already has is read up to its newest line.
*
* Room generates the shape -- `ChatRoom.lastReadMessageId`, `ChatRoom.notifications` and the
* `NotificationLedger` table -- and runs this after. Without it the column is null for every
* existing room, null reads as "nothing read", and the first launch of this build would show the
* user's entire history as unread. A user who had not read something before the upgrade has no
* way to have told us so, and "everything you had is read" is the only answer that does not
* invent one. docs/notifications-and-background-sync.md, Phase 3.
*/
class ReadMarkMigrationSpec : AutoMigrationSpec {
override suspend fun onPostMigrate(connection: SQLiteConnection) {
connection.execSQL(
"UPDATE `ChatRoom` SET `lastReadMessageId` = " +
"(SELECT MAX(`id`) FROM `ChatMessage` WHERE `ChatMessage`.`chatRoomId` = `ChatRoom`.`id`)"
)
}
}
@@ -167,6 +167,9 @@ data class ChatMessage(
* who can read it, because naming the recipient is the point of the line the
* bystanders get. See docs/marmot-direct-messages.md.
*/
/** An ordinary line of conversation: the default [messageType]. */
const val TYPE_MESSAGE = "message"
const val TYPE_DIRECT_MESSAGE = "directMessage"
/**
@@ -1,5 +1,6 @@
package mobi.giza.compose.database.model
import androidx.room3.ColumnInfo
import androidx.room3.Entity
import androidx.room3.ForeignKey
import androidx.room3.Ignore
@@ -138,6 +139,22 @@ data class ChatRoom(
*/
val parentChatRoomId: HexKey? = null,
/**
* The newest line the user has been shown in this room, by [ChatMessage.id], or null for
* none. A row id rather than a time because a line's time is the sender's claim and lines
* are written out of order -- "load older messages" files old lines now. Only ever moves
* forward. Local: no NIP says how to share it between devices.
* docs/notifications-and-background-sync.md, D8.
*/
val lastReadMessageId: Long? = null,
/**
* Whether this room may notify: [NOTIFICATIONS_ALL] or [NOTIFICATIONS_MUTED]. A muted room
* still counts what is unread; it only stays quiet about it.
*/
@ColumnInfo(defaultValue = NOTIFICATIONS_ALL)
val notifications: String = NOTIFICATIONS_ALL,
override val createdAt: Instant = Clock.System.now(),
override val updatedAt: Instant = createdAt,
override val savedAt: Instant = createdAt,
@@ -149,6 +166,9 @@ data class ChatRoom(
companion object {
const val TAG = "ChatRoom"
const val NOTIFICATIONS_ALL = "all"
const val NOTIFICATIONS_MUTED = "muted"
@Ignore
val logger = Logger.withTag(TAG)
@@ -0,0 +1,41 @@
package mobi.giza.compose.database.model
import androidx.room3.Entity
import androidx.room3.PrimaryKey
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlin.time.Instant
/**
* What one identity's notifications have got to, and how its last background sync went.
* docs/notifications-and-background-sync.md, D2 and D3.
*
* No row means not armed: nothing for that identity notifies until its first sync has settled
* and a row is written with the cursor at the newest line it then held. Otherwise signing in on
* a new phone would post one notification per message of history.
*
* Keyed by public key rather than by wallet id because every row it is compared against --
* `ChatRoom.userPublicKey` -- is.
*/
@Entity
data class NotificationLedger(
@PrimaryKey
val userPublicKey: HexKey,
/** When this identity started notifying. */
val armedAt: Instant,
/**
* The newest [ChatMessage.id] the dispatcher has decided about. A line above it is new to
* this device; one at or below it has been posted or dropped already. Only moves forward.
*/
val cursorMessageId: Long,
/** When a background pass last finished for this identity, however it finished. */
val lastBackgroundSyncAt: Instant? = null,
/** How it finished: `completed`, `deadline`, `noNetwork`, `visible`, `failed`. */
val lastBackgroundSyncOutcome: String? = null,
/** `quick` (to EOSE) or `full` (negentropy). */
val lastBackgroundSyncKind: String? = null,
)
@@ -0,0 +1,170 @@
package mobi.giza.compose.database
import androidx.room3.Room
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlin.time.Instant
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import mobi.giza.compose.database.builder.getRoomDatabase
import mobi.giza.compose.database.model.ChatMessage
import mobi.giza.compose.database.model.ChatRoom
import mobi.giza.compose.database.model.NostrEvent
import mobi.giza.compose.database.model.Profile
/**
* Read marks, the notification cursor and the ledger, over the app's own schema.
* docs/notifications-and-background-sync.md, Phase 3.
*/
class NotificationStorageJvmTest {
private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder<GizaDatabase>())
private val dao = db.notificationDao()
@AfterTest
fun closeDb() = db.close()
private val user = "a".repeat(64)
private val peer = "b".repeat(64)
private val roomOne = "11".repeat(32)
private val roomTwo = "22".repeat(32)
private suspend fun seedRooms() {
listOf(user, peer).forEach { publicKey ->
val eventId = publicKey.take(32).padEnd(64, 'c')
db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
db.profileDao().upsert(Profile(publicKey = publicKey, userName = publicKey.take(4), nostrEventId = eventId))
}
listOf(roomOne, roomTwo).forEach { id ->
db.chatRoomDao().upsert(ChatRoom(id = id, userPublicKey = user, subject = null, description = null, mlsGroupState = null))
}
}
private suspend fun line(
room: String = roomOne,
mine: Boolean = false,
type: String = ChatMessage.TYPE_MESSAGE,
): Long = db.chatMessageDao().upsert(
ChatMessage(
senderPublicKey = if (mine) user else peer,
isUserMessage = mine,
giftWrapPayloadId = null,
marmotGroupEventId = null,
marmotInnerEventId = null,
chatRoomId = room,
content = "hello",
messageType = type,
createdAt = Instant.fromEpochSeconds(1_800_000_000),
)
)
private suspend fun readMark(room: String) = assertNotNull(db.chatRoomDao().findChatRoomById(room)).chatRoom.lastReadMessageId
@Test
fun `a new room has nothing read and notifies`() = runBlocking {
seedRooms()
val room = assertNotNull(db.chatRoomDao().findChatRoomById(roomOne)).chatRoom
assertNull(room.lastReadMessageId)
assertEquals(ChatRoom.NOTIFICATIONS_ALL, room.notifications)
}
@Test
fun `unread counts the conversation said by others, above the mark`() = runBlocking {
seedRooms()
line()
line(mine = true)
line(type = ChatMessage.TYPE_FROST_STARTED)
val directMessage = line(type = ChatMessage.TYPE_DIRECT_MESSAGE)
assertEquals(2, dao.unreadCount(roomOne))
dao.markRead(roomOne, directMessage)
assertEquals(0, dao.unreadCount(roomOne))
line()
assertEquals(1, dao.unreadCount(roomOne))
assertEquals(listOf(mobi.giza.compose.database.dao.RoomUnread(roomOne, 1)), dao.observeUnreadCounts(user).first())
}
@Test
fun `a read mark never moves back`() = runBlocking {
seedRooms()
val first = line()
val second = line()
dao.markRead(roomOne, second)
assertEquals(0, dao.markRead(roomOne, first), "an older mark was written over a newer one")
assertEquals(second, readMark(roomOne))
}
@Test
fun `marking a room all read takes it to its newest line, and is a no-op when it already is`() = runBlocking {
seedRooms()
line()
val newest = line()
assertEquals(1, dao.markAllRead(roomOne))
assertEquals(newest, readMark(roomOne))
assertEquals(0, dao.markAllRead(roomOne), "a room already read was written again")
}
@Test
fun `nothing is new for an identity that is not armed`() = runBlocking {
seedRooms()
line()
assertNull(dao.getLedger(user))
}
/** D3: arming starts from what the device already holds, and reads it all. */
@Test
fun `arming puts the cursor at the newest line and reads every room`() = runBlocking {
seedRooms()
line(roomOne)
val newest = line(roomTwo)
assertTrue(dao.arm(user, Instant.fromEpochSeconds(1_800_000_100)))
val ledger = assertNotNull(dao.getLedger(user))
assertEquals(newest, ledger.cursorMessageId)
assertEquals(0, dao.unreadCount(roomOne))
assertEquals(0, dao.unreadCount(roomTwo))
assertTrue(dao.getAfter(user, ledger.cursorMessageId).isEmpty())
val arrived = line(roomOne)
assertEquals(listOf(arrived), dao.getAfter(user, ledger.cursorMessageId).map { it.id })
assertFalse(dao.arm(user, Instant.fromEpochSeconds(1_800_000_200)), "armed twice")
assertEquals(newest, assertNotNull(dao.getLedger(user)).cursorMessageId, "re-arming moved the cursor")
}
@Test
fun `the cursor never moves back`() = runBlocking {
seedRooms()
dao.arm(user, Instant.fromEpochSeconds(1_800_000_000))
dao.advanceCursor(user, 10)
assertEquals(0, dao.advanceCursor(user, 5))
assertEquals(10, assertNotNull(dao.getLedger(user)).cursorMessageId)
}
@Test
fun `a background sync is recorded on the ledger`() = runBlocking {
seedRooms()
dao.arm(user, Instant.fromEpochSeconds(1_800_000_000))
dao.recordBackgroundSync(user, Instant.fromEpochSeconds(1_800_000_500), "completed", "full")
val ledger = assertNotNull(dao.getLedger(user))
assertEquals(Instant.fromEpochSeconds(1_800_000_500), ledger.lastBackgroundSyncAt)
assertEquals("completed", ledger.lastBackgroundSyncOutcome)
assertEquals("full", ledger.lastBackgroundSyncKind)
}
@Test
fun `muting a room is stored on it`() = runBlocking {
seedRooms()
dao.setNotifications(roomOne, ChatRoom.NOTIFICATIONS_MUTED)
assertEquals(ChatRoom.NOTIFICATIONS_MUTED, assertNotNull(db.chatRoomDao().findChatRoomById(roomOne)).chatRoom.notifications)
}
}
@@ -0,0 +1,140 @@
package mobi.giza.compose.database.migrations
import androidx.room3.Room
import androidx.sqlite.SQLiteConnection
import androidx.sqlite.driver.bundled.BundledSQLiteDriver
import androidx.sqlite.execSQL
import java.io.File
import java.nio.file.Files
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.builder.getRoomDatabase
import mobi.giza.compose.database.model.ChatRoom
/**
* 46 -> 47: the read marks start where the history ends, so an upgrade does not make every line the
* user has ever had unread. docs/notifications-and-background-sync.md, Phase 3.
*
* Built from the exported v46 schema, as [ShippedProfileUpgradeJvmTest] builds its v36, so the
* fixture's tables and identity hash are a v46 install's.
*/
class ReadMarkMigrationJvmTest {
private val directory: File = Files.createTempDirectory("giza-read-mark").toFile()
private val file: File = File(directory, "aux.db")
@AfterTest
fun cleanUp() {
directory.deleteRecursively()
}
private val schemas: File =
(File("schemas").takeIf { it.isDirectory } ?: File("composeApp/schemas"))
.resolve("mobi.giza.compose.database.GizaDatabase")
private fun schema(version: Int): JsonObject =
Json.parseToJsonElement(schemas.resolve("$version.json").readText()).jsonObject["database"]!!.jsonObject
private fun entities(version: Int) = schema(version)["entities"]!!.jsonArray.map { it.jsonObject }
private val user = "f".repeat(64)
private val talkedIn = "a".repeat(64)
private val alsoTalkedIn = "b".repeat(64)
private val quiet = "c".repeat(64)
private fun writeV46() {
BundledSQLiteDriver().open(file.absolutePath).use { connection ->
entities(46).forEach { entity ->
val table = entity["tableName"]!!.jsonPrimitive.content
connection.execSQL(entity["createSql"]!!.jsonPrimitive.content.replace("\${TABLE_NAME}", table))
entity["indices"]?.jsonArray.orEmpty().forEach { index ->
connection.execSQL(index.jsonObject["createSql"]!!.jsonPrimitive.content.replace("\${TABLE_NAME}", table))
}
}
schema(46)["setupQueries"]!!.jsonArray.forEach { connection.execSQL(it.jsonPrimitive.content) }
connection.execSQL("PRAGMA user_version = 46")
insert(connection, "NostrEvent", mapOf("id" to "e".repeat(64), "pubKey" to user))
insert(connection, "Profile", mapOf("publicKey" to user, "nostrEventId" to "e".repeat(64)))
listOf(talkedIn, alsoTalkedIn, quiet).forEach {
insert(connection, "ChatRoom", mapOf("id" to it, "userPublicKey" to user, "mlsGroupState" to null))
}
listOf(talkedIn, alsoTalkedIn, talkedIn, alsoTalkedIn, talkedIn).forEachIndexed { index, room ->
insert(
connection,
"ChatMessage",
mapOf(
"id" to (index + 1).toLong(),
"chatRoomId" to room,
"giftWrapPayloadId" to null,
"marmotGroupEventId" to null,
"marmotInnerEventId" to null,
),
)
}
}
}
/** A row with [values], every other NOT NULL column without a default given a placeholder. */
private fun insert(connection: SQLiteConnection, table: String, values: Map<String, Any?>) {
val entity = entities(46).single { it["tableName"]!!.jsonPrimitive.content == table }
val filled = LinkedHashMap<String, Any?>()
entity["fields"]!!.jsonArray.map { it.jsonObject }.forEach { field ->
val column = field["columnName"]!!.jsonPrimitive.content
val notNull = field["notNull"]?.jsonPrimitive?.booleanOrNull == true
when {
column in values -> filled[column] = values[column]
notNull && field["defaultValue"] == null -> filled[column] = when (field["affinity"]!!.jsonPrimitive.content) {
"TEXT" -> "x"
"BLOB" -> ByteArray(0)
else -> 1L
}
}
}
val sql = "INSERT INTO `$table` (${filled.keys.joinToString(", ") { "`$it`" }}) " +
"VALUES (${filled.keys.joinToString(", ") { "?" }})"
connection.prepare(sql).use { statement ->
filled.values.forEachIndexed { position, value ->
val index = position + 1
when (value) {
null -> statement.bindNull(index)
is String -> statement.bindText(index, value)
is ByteArray -> statement.bindBlob(index, value)
is Long -> statement.bindLong(index, value)
else -> error("no binding for a ${value::class.simpleName}")
}
}
statement.step()
}
}
@Test
fun `every room an upgraded install has is read up to its newest line`(): Unit = runBlocking {
writeV46()
val database = getRoomDatabase(Room.databaseBuilder<GizaDatabase>(name = file.absolutePath))
try {
suspend fun room(id: String) = assertNotNull(database.chatRoomDao().findChatRoomById(id)).chatRoom
assertEquals(5L, room(talkedIn).lastReadMessageId)
assertEquals(4L, room(alsoTalkedIn).lastReadMessageId)
assertNull(room(quiet).lastReadMessageId, "a room with no lines was given a mark")
assertEquals(ChatRoom.NOTIFICATIONS_ALL, room(quiet).notifications)
assertEquals(0, database.notificationDao().unreadCount(talkedIn))
assertNull(database.notificationDao().getLedger(user), "an upgrade armed notifications by itself")
} finally {
database.close()
}
}
}
@@ -67,10 +67,11 @@ class ShippedProfileUpgradeJvmTest {
* 10), 41 for governance proposals and 42 for what follows them
* (docs/member-admin-promotion.md, Phases 5, 8 and 9), 43 for the confederation
* (docs/confederation.md, Phase 4), 44 for its key ceremony (Phase 11), 45 for its signing
* (Phase 14) and 46 for the group's inbox (docs/group-inbox.md, Phase 3), so the upgrade
* crosses ten generated migrations and the file has to come out at the last.
* (Phase 14), 46 for the group's inbox (docs/group-inbox.md, Phase 3) and 47 for
* notifications' read marks and ledger (docs/notifications-and-background-sync.md, Phase 3), so
* the upgrade crosses eleven generated migrations and the file has to come out at the last.
*/
private val current = 46
private val current = 47
private val directory: File = Files.createTempDirectory("giza-shipped-profile").toFile()
private val file: File = File(directory, "aux.db")