feat: storage for disappearing messages, v50 (disappearing-messages, Phase 2)
A conversation's override and one-time notice on ChatRoom, an expiry on ChatMessage, GiftWrapPayload (read off its own tags) and GiftWrapMessage, a wrap's link to its payload, and the DisappearingSetting and ExpiredGiftWrap tables. Nullable columns and new tables only, so Room generates the migration; a missing setting reads as the one-day default. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
962bdbf631
commit
b7f6df0c3b
13 files changed
+7881
-5
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -12,6 +12,7 @@ import mobi.giza.compose.database.converters.GizaConverters
|
||||
import mobi.giza.compose.database.dao.BroadcastNostrEventReceiptDao
|
||||
import mobi.giza.compose.database.dao.ConfederationCeremonyDao
|
||||
import mobi.giza.compose.database.dao.ConfederationDao
|
||||
import mobi.giza.compose.database.dao.DisappearingDao
|
||||
import mobi.giza.compose.database.dao.BroadcastNostrEventRequestDao
|
||||
import mobi.giza.compose.database.dao.ChatMessageBroadcastNostrEventReceiptRelationDao
|
||||
import mobi.giza.compose.database.dao.ChatMessageBroadcastNostrEventRequestRelationDao
|
||||
@@ -73,6 +74,8 @@ import mobi.giza.compose.database.model.ChatMessageBroadcastNostrEventRequestRel
|
||||
import mobi.giza.compose.database.model.ChatMessageNostrEventRelation
|
||||
import mobi.giza.compose.database.model.ChatRoom
|
||||
import mobi.giza.compose.database.model.Confederation
|
||||
import mobi.giza.compose.database.model.DisappearingSetting
|
||||
import mobi.giza.compose.database.model.ExpiredGiftWrap
|
||||
import mobi.giza.compose.database.model.GroupConversationKey
|
||||
import mobi.giza.compose.database.model.GroupDmMessage
|
||||
import mobi.giza.compose.database.model.GroupDmOutbound
|
||||
@@ -158,6 +161,8 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
|
||||
ChatMessageNostrEventRelation::class,
|
||||
ChatRoom::class,
|
||||
Confederation::class,
|
||||
DisappearingSetting::class,
|
||||
ExpiredGiftWrap::class,
|
||||
ConfederationCeremony::class,
|
||||
ConfederationMember::class,
|
||||
ConfederationSigningAttempt::class,
|
||||
@@ -227,7 +232,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
|
||||
UnsignedNostrEvent::class,
|
||||
Zap::class
|
||||
],
|
||||
version = 49,
|
||||
version = 50,
|
||||
autoMigrations = [
|
||||
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
|
||||
// generate the migration itself — nothing existing changes shape.
|
||||
@@ -523,6 +528,13 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
|
||||
// statements, never in a release, are dropped; the ceremony loses its coordinator; and a
|
||||
// confederation records whose MLS group it holds as its room. See ConfederationSupergroupMigration.
|
||||
AutoMigration(from = 48, to = 49, spec = ConfederationSupergroupMigration::class),
|
||||
// v50 adds disappearing messages' storage (docs/disappearing-messages.md, Phase 2): the
|
||||
// nullable ChatRoom.disappearingMessageSecs and disappearingNoticeShownAt, the nullable
|
||||
// ChatMessage.expiresAt and GiftWrapPayload.expiresAt with an index each, and the
|
||||
// DisappearingSetting and ExpiredGiftWrap tables. Nullable columns and new tables only, so
|
||||
// Room generates it. No data moves: an identity with no DisappearingSetting row reads as
|
||||
// the one-day default, which is D9's upgrade without a data step.
|
||||
AutoMigration(from = 49, to = 50),
|
||||
]
|
||||
)
|
||||
@ConstructedBy(GizaDatabaseConstructor::class)
|
||||
@@ -551,6 +563,8 @@ abstract class GizaDatabase: RoomDatabase() {
|
||||
|
||||
abstract fun confederationDao(): ConfederationDao
|
||||
|
||||
abstract fun disappearingDao(): DisappearingDao
|
||||
|
||||
abstract fun confederationCeremonyDao(): ConfederationCeremonyDao
|
||||
|
||||
abstract fun dkgSessionDao(): DkgSessionDao
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package mobi.giza.compose.database.dao
|
||||
|
||||
import androidx.room3.Dao
|
||||
import androidx.room3.Insert
|
||||
import androidx.room3.OnConflictStrategy
|
||||
import androidx.room3.Query
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import kotlin.time.Instant
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import mobi.giza.compose.database.model.DisappearingSetting
|
||||
import mobi.giza.compose.database.model.ExpiredGiftWrap
|
||||
|
||||
/** The settings and the tombstones of docs/disappearing-messages.md. */
|
||||
@Dao
|
||||
abstract class DisappearingDao {
|
||||
|
||||
// -- the identity's default (D4) ---------------------------------------------------------
|
||||
|
||||
@Query("SELECT defaultSeconds FROM DisappearingSetting WHERE userPublicKey = :userPublicKey")
|
||||
abstract suspend fun getDefault(userPublicKey: HexKey): Long?
|
||||
|
||||
@Query("SELECT defaultSeconds FROM DisappearingSetting WHERE userPublicKey = :userPublicKey")
|
||||
abstract fun observeDefault(userPublicKey: HexKey): Flow<Long?>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
abstract suspend fun upsertSetting(setting: DisappearingSetting)
|
||||
|
||||
// -- a conversation's override (D4) ------------------------------------------------------
|
||||
|
||||
@Query("SELECT disappearingMessageSecs FROM ChatRoom WHERE id = :chatRoomId")
|
||||
abstract suspend fun getRoomOverride(chatRoomId: String): Long?
|
||||
|
||||
@Query("SELECT disappearingMessageSecs FROM ChatRoom WHERE id = :chatRoomId")
|
||||
abstract fun observeRoomOverride(chatRoomId: String): Flow<Long?>
|
||||
|
||||
@Query("UPDATE ChatRoom SET disappearingMessageSecs = :seconds WHERE id = :chatRoomId")
|
||||
abstract suspend fun setRoomOverride(chatRoomId: String, seconds: Long?): Int
|
||||
|
||||
@Query("SELECT userPublicKey FROM ChatRoom WHERE id = :chatRoomId")
|
||||
abstract suspend fun ownerOf(chatRoomId: String): HexKey?
|
||||
|
||||
// -- the one-time notice (D9) ------------------------------------------------------------
|
||||
|
||||
@Query("SELECT disappearingNoticeShownAt FROM ChatRoom WHERE id = :chatRoomId")
|
||||
abstract suspend fun noticeShownAt(chatRoomId: String): Instant?
|
||||
|
||||
@Query("UPDATE ChatRoom SET disappearingNoticeShownAt = :at WHERE id = :chatRoomId AND disappearingNoticeShownAt IS NULL")
|
||||
abstract suspend fun markNoticeShown(chatRoomId: String, at: Instant): Int
|
||||
|
||||
// -- tombstones (D6) ---------------------------------------------------------------------
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
abstract suspend fun tombstone(wrap: ExpiredGiftWrap)
|
||||
|
||||
@Query("SELECT EXISTS (SELECT 1 FROM ExpiredGiftWrap WHERE id = :wrapId)")
|
||||
abstract suspend fun isTombstoned(wrapId: HexKey): Boolean
|
||||
|
||||
@Query("DELETE FROM ExpiredGiftWrap WHERE dropAfter <= :now")
|
||||
abstract suspend fun pruneTombstones(now: Instant): Int
|
||||
}
|
||||
@@ -83,7 +83,7 @@ import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent
|
||||
// room, and re-reads all of them each time a message lands anywhere. Without
|
||||
// this that is a scan of every message this device holds, per room, per
|
||||
// arrival -- work that grows with the whole history rather than with the room.
|
||||
indices = [Index("chatRoomId")],
|
||||
indices = [Index("chatRoomId"), Index("expiresAt")],
|
||||
)
|
||||
data class ChatMessage(
|
||||
@PrimaryKey(autoGenerate = true)
|
||||
@@ -112,6 +112,13 @@ data class ChatMessage(
|
||||
*/
|
||||
val directMessageRecipientPublicKey: HexKey? = null,
|
||||
|
||||
/**
|
||||
* When this line disappears, from its rumor's NIP-40 `expiration`, or null for never. The
|
||||
* sweeper deletes it, and everything holding its words, from then on; a line that arrives
|
||||
* already past it is never filed. docs/disappearing-messages.md, D6.
|
||||
*/
|
||||
val expiresAt: Instant? = null,
|
||||
|
||||
/**
|
||||
* The signing session a [FROST_TYPES] line belongs to, or null for anything else.
|
||||
*
|
||||
|
||||
@@ -155,6 +155,17 @@ data class ChatRoom(
|
||||
@ColumnInfo(defaultValue = NOTIFICATIONS_ALL)
|
||||
val notifications: String = NOTIFICATIONS_ALL,
|
||||
|
||||
/**
|
||||
* How long what the user writes here lasts, in seconds: null follows the identity's default,
|
||||
* `0` is Off for this conversation only. Read once per message, when it is queued, and only in
|
||||
* a NIP-17 room -- an MLS room follows the group's own retention. Local: NIP-17 has no shared
|
||||
* timer, so each sender's choice rides their own messages. docs/disappearing-messages.md, D4.
|
||||
*/
|
||||
val disappearingMessageSecs: Long? = null,
|
||||
|
||||
/** When the one-time "messages now disappear" notice was shown here, or null for not yet (D9). */
|
||||
val disappearingNoticeShownAt: Instant? = null,
|
||||
|
||||
override val createdAt: Instant = Clock.System.now(),
|
||||
override val updatedAt: Instant = createdAt,
|
||||
override val savedAt: Instant = createdAt,
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
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
|
||||
|
||||
/**
|
||||
* An identity's default for how long what it writes in NIP-17 conversations lasts, in seconds;
|
||||
* `0` is Off. No row reads as [mobi.giza.compose.nostr.DisappearingMessages.DEFAULT_SECONDS], which
|
||||
* is how a new identity and an upgraded one both start at a day without a data migration.
|
||||
* docs/disappearing-messages.md, D4 and D9.
|
||||
*/
|
||||
@Entity
|
||||
data class DisappearingSetting(
|
||||
@PrimaryKey
|
||||
val userPublicKey: HexKey,
|
||||
val defaultSeconds: Long,
|
||||
val updatedAt: Instant,
|
||||
)
|
||||
|
||||
/**
|
||||
* A gift wrap this device has already handled and deleted, kept until the wrap's own expiry so a
|
||||
* re-sync that brings it back is dropped before it is decrypted again. The wrap outlives its rumor
|
||||
* by up to two days on a relay, by design. docs/disappearing-messages.md, D6.
|
||||
*/
|
||||
@Entity
|
||||
data class ExpiredGiftWrap(
|
||||
@PrimaryKey
|
||||
val id: HexKey,
|
||||
val dropAfter: Instant,
|
||||
)
|
||||
@@ -3,6 +3,7 @@ package mobi.giza.compose.database.model
|
||||
import androidx.room3.Entity
|
||||
import androidx.room3.ForeignKey
|
||||
import androidx.room3.Ignore
|
||||
import androidx.room3.Index
|
||||
import androidx.room3.PrimaryKey
|
||||
import co.touchlab.kermit.Logger
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
@@ -25,6 +26,7 @@ import kotlin.time.Instant
|
||||
onDelete = ForeignKey.CASCADE,
|
||||
),
|
||||
],
|
||||
indices = [Index("giftWrapPayloadId"), Index("expiresAt")],
|
||||
)
|
||||
data class GiftWrapMessage(
|
||||
@PrimaryKey
|
||||
@@ -72,6 +74,22 @@ data class GiftWrapMessage(
|
||||
override val savedAt: Instant = Clock.System.now(),
|
||||
override val viewedAt: Instant? = null,
|
||||
override val deletedAt: Instant? = null, // Who this message should be seen by (used to derive conversationId)
|
||||
|
||||
/**
|
||||
* The payload this wrap carried, when this device knows it: every wrap it sealed, and every
|
||||
* wrap it opened. Not a foreign key, on purpose -- the cascade already runs the other way,
|
||||
* wrap to seal to payload -- but it is how the sweeper finds all of a payload's wraps, the
|
||||
* sender's one-per-recipient copies included, and deletes them with it rather than before it.
|
||||
* docs/disappearing-messages.md, Phase 4.
|
||||
*/
|
||||
val giftWrapPayloadId: HexKey? = null,
|
||||
|
||||
/**
|
||||
* When this device drops the wrap: its payload's expiry when that is known, else the wrap's
|
||||
* own NIP-40 `expiration` -- a wrap addressed to somebody else is kept, unopened, and goes
|
||||
* when the relay would have dropped it. Null for never. docs/disappearing-messages.md, D6.
|
||||
*/
|
||||
val expiresAt: Instant? = null,
|
||||
): mobi.giza.compose.database.model.traits.NostrEventEntity,
|
||||
mobi.giza.compose.database.model.traits.TimestampedEntity,
|
||||
mobi.giza.compose.database.model.traits.LocalStoreEntity,
|
||||
|
||||
@@ -3,6 +3,7 @@ package mobi.giza.compose.database.model
|
||||
import androidx.room3.Entity
|
||||
import androidx.room3.ForeignKey
|
||||
import androidx.room3.Ignore
|
||||
import androidx.room3.Index
|
||||
import androidx.room3.PrimaryKey
|
||||
import mobi.giza.compose.database.model.traits.LocalStoreEntity
|
||||
import mobi.giza.compose.database.model.traits.SoftDeletableEntity
|
||||
@@ -17,6 +18,7 @@ import com.vitorpamplona.quartz.nip01Core.tags.people.taggedUsers
|
||||
import com.vitorpamplona.quartz.nip14Subject.subject
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Instant
|
||||
import mobi.giza.compose.nostr.DisappearingMessages
|
||||
|
||||
@Entity(
|
||||
foreignKeys = [
|
||||
@@ -27,6 +29,7 @@ import kotlin.time.Instant
|
||||
onDelete = ForeignKey.CASCADE,
|
||||
)
|
||||
],
|
||||
indices = [Index("expiresAt")],
|
||||
)
|
||||
data class GiftWrapPayload(
|
||||
@PrimaryKey
|
||||
@@ -78,6 +81,14 @@ data class GiftWrapPayload(
|
||||
override val savedAt: Instant = Clock.System.now(),
|
||||
override val viewedAt: Instant? = null,
|
||||
override val deletedAt: Instant? = null, // Who this message should be seen by (used to derive conversationId)
|
||||
|
||||
/**
|
||||
* The rumor's NIP-40 `expiration`, or null for never. Read off [tags] by default, so every
|
||||
* producer -- and the inbound path, which builds this from an unsealed rumor -- records it
|
||||
* without saying so, and the sweeper finds what is due without parsing every row's tags.
|
||||
* docs/disappearing-messages.md, D2 and D6.
|
||||
*/
|
||||
val expiresAt: Instant? = DisappearingMessages.expirationOf(tags, createdAt.epochSeconds)?.let { Instant.fromEpochSeconds(it) },
|
||||
): TimestampedEntity, LocalStoreEntity, UserViewableEntity, SoftDeletableEntity {
|
||||
@Ignore
|
||||
private val logger = Logger.withTag(TAG)
|
||||
@@ -132,6 +143,7 @@ data class GiftWrapPayload(
|
||||
if (content != other.content) return false
|
||||
if (quotedEventId != other.quotedEventId) return false
|
||||
if (giftWrapSealId != other.giftWrapSealId) return false
|
||||
if (expiresAt != other.expiresAt) return false
|
||||
if (createdAt != other.createdAt) return false
|
||||
if (updatedAt != other.updatedAt) return false
|
||||
if (savedAt != other.savedAt) return false
|
||||
@@ -149,6 +161,7 @@ data class GiftWrapPayload(
|
||||
result = 31 * result + content.hashCode()
|
||||
result = 31 * result + (quotedEventId?.hashCode() ?: 0)
|
||||
result = 31 * result + (giftWrapSealId?.hashCode() ?: 0)
|
||||
result = 31 * result + (expiresAt?.hashCode() ?: 0)
|
||||
result = 31 * result + createdAt.hashCode()
|
||||
result = 31 * result + updatedAt.hashCode()
|
||||
result = 31 * result + savedAt.hashCode()
|
||||
|
||||
@@ -209,6 +209,10 @@ data class NostrEvent(
|
||||
receiverRelayHit = receiverPTag.relayHint?.url,
|
||||
signature = giftWrapEvent.sig,
|
||||
nostrEventId = id,
|
||||
// The wrap's own expiry until it is opened; filing what it carries replaces
|
||||
// this with the rumor's (docs/disappearing-messages.md, D6).
|
||||
expiresAt = mobi.giza.compose.nostr.DisappearingMessages.expirationOf(tags, createdAt.epochSeconds)
|
||||
?.let { Instant.fromEpochSeconds(it) },
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package mobi.giza.compose.database.repository
|
||||
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Kind
|
||||
import kotlin.time.Clock
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import mobi.giza.compose.database.GizaDatabase
|
||||
import mobi.giza.compose.database.model.DisappearingSetting
|
||||
import mobi.giza.compose.nostr.DisappearingMessages
|
||||
|
||||
/**
|
||||
* How long what a person writes lasts: their default, and a conversation's override.
|
||||
* docs/disappearing-messages.md, D4. The screens read and write through this; the send path asks
|
||||
* [policyFor] once per message.
|
||||
*/
|
||||
class DisappearingSettingsStore(private val database: GizaDatabase) {
|
||||
|
||||
/** The identity's default, a day until they choose otherwise. */
|
||||
suspend fun defaultFor(userPublicKey: HexKey): Long =
|
||||
database.disappearingDao().getDefault(userPublicKey) ?: DisappearingMessages.DEFAULT_SECONDS
|
||||
|
||||
fun observeDefault(userPublicKey: HexKey): Flow<Long> =
|
||||
database.disappearingDao().observeDefault(userPublicKey).map { it ?: DisappearingMessages.DEFAULT_SECONDS }
|
||||
|
||||
suspend fun saveDefault(userPublicKey: HexKey, seconds: Long) {
|
||||
require(DisappearingMessages.isValidPolicy(seconds)) { "Not a policy: $seconds seconds" }
|
||||
database.disappearingDao().upsertSetting(DisappearingSetting(userPublicKey, seconds, Clock.System.now()))
|
||||
}
|
||||
|
||||
/** The conversation's own setting: null follows the default, `0` is Off here only. */
|
||||
fun observeOverride(chatRoomId: String): Flow<Long?> = database.disappearingDao().observeRoomOverride(chatRoomId)
|
||||
|
||||
suspend fun saveOverride(chatRoomId: String, seconds: Long?) {
|
||||
require(seconds == null || DisappearingMessages.isValidPolicy(seconds)) { "Not a policy: $seconds seconds" }
|
||||
database.disappearingDao().setRoomOverride(chatRoomId, seconds)
|
||||
}
|
||||
|
||||
/** The policy a message queued now in [chatRoomId] by [userPublicKey] is stamped with. */
|
||||
suspend fun policyFor(chatRoomId: String, userPublicKey: HexKey): Long =
|
||||
DisappearingMessages.policyFor(database.disappearingDao().getRoomOverride(chatRoomId), defaultFor(userPublicKey))
|
||||
|
||||
/**
|
||||
* [tags] with the rumor's expiry under the room's policy: what every producer of a NIP-17
|
||||
* `GiftWrapPayload` calls *before* it hashes the rumor's id, since the tag is one of the fields
|
||||
* the id covers. docs/disappearing-messages.md, Phase 3.
|
||||
*/
|
||||
suspend fun stamp(chatRoomId: String, userPublicKey: HexKey, kind: Kind, createdAt: Long, tags: Array<Array<String>>): Array<Array<String>> =
|
||||
DisappearingMessages.stamp(kind, createdAt, policyFor(chatRoomId, userPublicKey), tags)
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
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.assertFalse
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import kotlin.time.Instant
|
||||
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.ExpiredGiftWrap
|
||||
import mobi.giza.compose.database.repository.DisappearingSettingsStore
|
||||
import mobi.giza.compose.nostr.DisappearingMessages
|
||||
|
||||
/**
|
||||
* 49 -> 50: disappearing messages' storage arrives empty, and an upgraded identity reads as the
|
||||
* one-day default without a data step. docs/disappearing-messages.md, Phase 2 and D9.
|
||||
*
|
||||
* Built from the exported v49 schema, as [ReadMarkMigrationJvmTest] builds its v47.
|
||||
*/
|
||||
class DisappearingMessagesMigrationJvmTest {
|
||||
|
||||
private val directory: File = Files.createTempDirectory("giza-disappearing").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 nip17Room = "a".repeat(64)
|
||||
private val payload = "b".repeat(64)
|
||||
|
||||
private fun writeV49() {
|
||||
BundledSQLiteDriver().open(file.absolutePath).use { connection ->
|
||||
entities(49).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(49)["setupQueries"]!!.jsonArray.forEach { connection.execSQL(it.jsonPrimitive.content) }
|
||||
connection.execSQL("PRAGMA user_version = 49")
|
||||
|
||||
insert(connection, "NostrEvent", mapOf("id" to "e".repeat(64), "pubKey" to user))
|
||||
insert(connection, "Profile", mapOf("publicKey" to user, "nostrEventId" to "e".repeat(64)))
|
||||
insert(connection, "ChatRoom", mapOf("id" to nip17Room, "userPublicKey" to user, "mlsGroupState" to null, "initialGiftWrapPayloadId" to null))
|
||||
insert(
|
||||
connection,
|
||||
"GiftWrapPayload",
|
||||
mapOf("id" to payload, "publicKey" to user, "chatRoomId" to nip17Room, "kind" to 14L, "giftWrapSealId" to null),
|
||||
)
|
||||
insert(
|
||||
connection,
|
||||
"ChatMessage",
|
||||
mapOf(
|
||||
"id" to 1L,
|
||||
"chatRoomId" to nip17Room,
|
||||
"giftWrapPayloadId" to payload,
|
||||
"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(49).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" -> if (column == "tags") "[]" else "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 `an upgraded install keeps its messages, has no expiries, and defaults to a day`(): Unit = runBlocking {
|
||||
writeV49()
|
||||
|
||||
val database = getRoomDatabase(Room.databaseBuilder<GizaDatabase>(name = file.absolutePath))
|
||||
try {
|
||||
val room = assertNotNull(database.chatRoomDao().findChatRoomById(nip17Room)).chatRoom
|
||||
assertNull(room.disappearingMessageSecs, "an upgraded room was given an override")
|
||||
assertNull(room.disappearingNoticeShownAt, "the one-time notice counts as shown")
|
||||
|
||||
val line = assertNotNull(database.chatMessageDao().getChatMessagesByGiftWrapPayloadId(payload))
|
||||
assertNull(line.expiresAt, "a message sent before the upgrade was given an expiry")
|
||||
assertNull(assertNotNull(database.giftWrapPayloadDao().getById(payload)).expiresAt)
|
||||
|
||||
val store = DisappearingSettingsStore(database)
|
||||
assertNull(database.disappearingDao().getDefault(user), "an upgrade wrote a setting")
|
||||
assertEquals(DisappearingMessages.DEFAULT_SECONDS, store.defaultFor(user))
|
||||
assertEquals(DisappearingMessages.DEFAULT_SECONDS, store.policyFor(nip17Room, user))
|
||||
} finally {
|
||||
database.close()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `the override wins, Off is a value, and the default can change`(): Unit = runBlocking {
|
||||
writeV49()
|
||||
|
||||
val database = getRoomDatabase(Room.databaseBuilder<GizaDatabase>(name = file.absolutePath))
|
||||
try {
|
||||
val store = DisappearingSettingsStore(database)
|
||||
store.saveDefault(user, DisappearingMessages.HOUR)
|
||||
assertEquals(DisappearingMessages.HOUR, store.policyFor(nip17Room, user))
|
||||
store.saveOverride(nip17Room, DisappearingMessages.OFF)
|
||||
assertEquals(DisappearingMessages.OFF, store.policyFor(nip17Room, user))
|
||||
store.saveOverride(nip17Room, null)
|
||||
assertEquals(DisappearingMessages.HOUR, store.policyFor(nip17Room, user))
|
||||
} finally {
|
||||
database.close()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a tombstone lasts until its wrap would have`(): Unit = runBlocking {
|
||||
writeV49()
|
||||
|
||||
val database = getRoomDatabase(Room.databaseBuilder<GizaDatabase>(name = file.absolutePath))
|
||||
try {
|
||||
val dao = database.disappearingDao()
|
||||
dao.tombstone(ExpiredGiftWrap("c".repeat(64), Instant.fromEpochSeconds(2_000)))
|
||||
assertTrue(dao.isTombstoned("c".repeat(64)))
|
||||
assertEquals(0, dao.pruneTombstones(Instant.fromEpochSeconds(1_999)))
|
||||
assertEquals(1, dao.pruneTombstones(Instant.fromEpochSeconds(2_000)))
|
||||
assertFalse(dao.isTombstoned("c".repeat(64)))
|
||||
} finally {
|
||||
database.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -70,10 +70,11 @@ class ShippedProfileUpgradeJvmTest {
|
||||
* (Phase 14), 46 for the group's inbox (docs/group-inbox.md, Phase 3), 47 for a group's
|
||||
* direct messages by threshold ECDH (docs/group-threshold-ecdh.md, Phase 4), 48 for
|
||||
* notifications' read marks and ledger (docs/notifications-and-background-sync.md, Phase 3) and
|
||||
* 49 for the confederation's statements between inboxes (docs/confederation-without-coordinator.md), so
|
||||
* the upgrade crosses thirteen generated migrations and the file has to come out at the last.
|
||||
* 49 for the confederation's statements between inboxes (docs/confederation-without-coordinator.md) and
|
||||
* 50 for disappearing messages (docs/disappearing-messages.md, Phase 2), so the upgrade crosses
|
||||
* fourteen generated migrations and the file has to come out at the last.
|
||||
*/
|
||||
private val current = 49
|
||||
private val current = 50
|
||||
|
||||
private val directory: File = Files.createTempDirectory("giza-shipped-profile").toFile()
|
||||
private val file: File = File(directory, "aux.db")
|
||||
|
||||
@@ -405,6 +405,30 @@ Migration 49 → 50, following the pattern in `database/migrations/`:
|
||||
Tests: a migration JVM test in the style of `ReadMarkMigrationJvmTest`, run against a version-49
|
||||
database with NIP-17 and MLS rooms in it.
|
||||
|
||||
**Built.** `AutoMigration(from = 49, to = 50)`, with no spec, because nothing moves. It differs from
|
||||
the plan in two ways:
|
||||
|
||||
- The identity's default is a table of its own, `DisappearingSetting(userPublicKey, defaultSeconds)`,
|
||||
not a column of `NotificationLedger`. A ledger row exists only once notifications are armed, and
|
||||
a policy has to apply before that. A missing row reads as one day, so D9's upgrade needs no data
|
||||
step.
|
||||
- `ExpiredGiftWrap` holds inbound wrap ids only (D6 dropped the outbound tombstone).
|
||||
- `GiftWrapMessage` gains `giftWrapPayloadId` and `expiresAt`, which the plan did not have. The
|
||||
cascade runs wrap → seal → payload → chat line, so deleting a wrap early would delete an
|
||||
unfinished ceremony's round with it. The sender's one-per-recipient wraps also had no link to
|
||||
their payload at all, only the first seal did. The sweeper needs both columns (Phase 4).
|
||||
- `GiftWrapPayload.expiresAt` defaults to the value read off the row's own tags. Every producer
|
||||
and the inbound path therefore record it without being changed.
|
||||
|
||||
`DisappearingDao` and `DisappearingSettingsStore` sit beside them. `DisappearingMessagesMigrationJvmTest`
|
||||
covers the upgrade, the store and the tombstones, and `ShippedProfileUpgradeJvmTest` now expects
|
||||
version 50.
|
||||
|
||||
**Found while building, and Phase 4 has to handle it:** `ChatRoom.initialGiftWrapPayloadId` is a
|
||||
foreign key to `GiftWrapPayload` with `ON DELETE CASCADE`. `NostrDao` sets it to the payload that
|
||||
first created a NIP-17 room on this device. Deleting that payload would delete the whole
|
||||
conversation. The sweeper clears the reference before it deletes the payload.
|
||||
|
||||
### Phase 3: sending, for every kind
|
||||
|
||||
- **One place applies the policy.** A single `DisappearingMessages.stamp(payload, room,
|
||||
|
||||
Reference in new issue
Block a user