Yokan / rebuild
Course 1 8624561

RoomRecipeInstallationStoreTest.kt

composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/database/room/RoomRecipeInstallationStoreTest.kt

test / fixture268 lines
1package eu.friedcutlet.yokan.database.room23import androidx.room.Room4import eu.friedcutlet.yokan.services.extensions.recipe.TestClock5import androidx.room.useWriterConnection6import androidx.sqlite.execSQL7import androidx.sqlite.driver.bundled.BundledSQLiteDriver8import eu.friedcutlet.yokan.services.extensions.recipe.CatalogAcceptanceState9import eu.friedcutlet.yokan.services.extensions.recipe.CatalogSnapshotGeneration10import eu.friedcutlet.yokan.services.extensions.recipe.CatalogTrustPolicy11import eu.friedcutlet.yokan.services.extensions.recipe.InstalledRecipeRecord12import eu.friedcutlet.yokan.services.extensions.recipe.RecipeCatalogEnrollmentResult13import eu.friedcutlet.yokan.services.extensions.recipe.RecipeInstallCandidate14import eu.friedcutlet.yokan.services.extensions.recipe.RecipeInstallCommitResult15import eu.friedcutlet.yokan.services.extensions.recipe.RecipeInstallationClock16import eu.friedcutlet.yokan.services.extensions.recipe.RecipeInstallationStoreLimits17import eu.friedcutlet.yokan.services.extensions.recipe.TrustedCatalogKey18import eu.friedcutlet.yokan.services.extensions.recipe.TrustedCatalogKeyState19import eu.friedcutlet.yokan.services.extensions.recipe.recipeSourceId20import eu.friedcutlet.yokan.services.extensions.recipe.recipeSourceReference21import eu.friedcutlet.yokan.database.SnapshotReplacementConflictException22import eu.friedcutlet.yokan.database.seedDatabaseSnapshot23import java.io.File24import java.nio.file.Files25import kotlinx.serialization.json.Json26import kotlinx.serialization.json.jsonArray27import kotlinx.serialization.json.jsonObject28import kotlinx.serialization.json.jsonPrimitive29import kotlin.test.Test30import kotlin.test.assertEquals31import kotlin.test.assertFailsWith32import kotlin.test.assertNull33import kotlinx.coroutines.runBlocking3435class RoomRecipeInstallationStoreTest {36    private val catalogId = "catalog.primary"37    private val now = 1_700_000_000L3839    @Test40    fun v5FixtureMigratesAndRecipeSourcePersistsAcrossReopen() = runBlocking {41        val migrationDirectory = Files.createTempDirectory("yokan-recipe-v5")42        val migrationPath = migrationDirectory.resolve("yokan.db").toString()43        try {44            createV5Fixture(migrationPath)45            val migrated = openRoom(migrationPath)46            try {47                assertEquals(listOf(77L), migrated.mangaDao().all().map { it.id })48                assertEquals(emptyList(), migrated.recipeInstallationDao().allCheckpoints())49                assertEquals(emptyList(), migrated.recipeInstallationDao().trustKeys("catalog.primary"))50                assertEquals(emptyList(), migrated.recipeInstallationDao().installed("catalog.primary"))51            } finally {52                migrated.close()53            }54        } finally {55            migrationDirectory.toFile().deleteRecursively()56        }5758        withRoom { path, room ->59            val clock = TestClock(now)60            val store = RoomRecipeInstallationStore(room, clock)61            val policy = policy()62            assertEquals(RecipeCatalogEnrollmentResult.Created, store.enrollIfAbsent(catalogId, policy))63            assertEquals(RecipeCatalogEnrollmentResult.AlreadyExists, store.enrollIfAbsent(catalogId, policy.copy(trustedKeys = listOf(policy.trustedKeys.single().copy(keyId = "replacement")))))64            val before = store.readCatalog(catalogId)!!65            val stale = candidate(before, 11)66            assertEquals(RecipeInstallCommitResult.Applied, store.commitInstall(before.generation, candidate(before, 10, release = "a".repeat(80), digest = "a".repeat(64))))67            assertEquals(RecipeInstallCommitResult.Conflict, store.commitInstall(before.generation, stale))68            room.close()6970            val reopened = openRoom(path)71            try {72                val restored = RoomRecipeInstallationStore(reopened, clock).readCatalog(catalogId)!!73                assertEquals(1, restored.generation.value)74                assertEquals(10, restored.acceptanceState!!.highestRevision)75                assertEquals(listOf("recipe.one"), restored.installedRecords.keys.toList())76                val sourceId = recipeSourceId(catalogId, "recipe.one")77                assertEquals(sourceId, restored.installedRecords.getValue("recipe.one").sourceId)78                assertEquals("Recipe", reopened.sourceDao().source(sourceId)?.typeSource)79                assertEquals(recipeSourceReference(catalogId, "recipe.one"), reopened.sourceDao().source(sourceId)?.additionalParams)80                assertEquals(true, reopened.sourceDao().source(sourceId)?.isAdded, "installed recipes must be listed in Browse")81                assertEquals("a".repeat(80), restored.installedRecords.getValue("recipe.one").releaseVersion)82                assertEquals("a".repeat(64), restored.installedRecords.getValue("recipe.one").sha256)83                assertEquals(policy.trustedKeys.single().rawEd25519PublicKey.toList(), restored.trustPolicy.trustedKeys.single().rawEd25519PublicKey.toList())84            } finally {85                reopened.close()86            }87        }88    }8990    @Test91    fun casClockQuotaAndCorruptionFailClosed() = runBlocking {92        withRoom { _, room ->93            val clock = TestClock(now)94            val store = RoomRecipeInstallationStore(room, clock, RecipeInstallationStoreLimits(2, 2, 1, 1))95            assertEquals(RecipeCatalogEnrollmentResult.Created, store.enrollIfAbsent(catalogId, policy(validUntil = now)))96            val initial = store.readCatalog(catalogId)!!97            clock.value = now + 198            assertEquals(RecipeInstallCommitResult.Rejected, store.commitInstall(initial.generation, candidate(initial, 10, artifact = byteArrayOf(1))))99            assertNull(store.readCatalog(catalogId)!!.acceptanceState)100            assertEquals(0, store.readCatalog(catalogId)!!.generation.value)101102        }103104        withRoom { _, room ->105            val quotaStore = RoomRecipeInstallationStore(room, TestClock(now), RecipeInstallationStoreLimits(2, 2, 1, 1))106            assertEquals(RecipeCatalogEnrollmentResult.Created, quotaStore.enrollIfAbsent(catalogId, policy()))107            val quotaInitial = quotaStore.readCatalog(catalogId)!!108            assertEquals(RecipeInstallCommitResult.Rejected, quotaStore.commitInstall(quotaInitial.generation, candidate(quotaInitial, 10, artifact = byteArrayOf(1, 2))))109            assertNull(quotaStore.readCatalog(catalogId)!!.acceptanceState)110            assertEquals(0, quotaStore.readCatalog(catalogId)!!.generation.value)111        }112113        withRoom { _, room ->114            room.recipeInstallationDao().insertCheckpoint(RecipeCatalogCheckpointRow("corrupt.catalog", 0))115            assertFailsWith<IllegalStateException> { RoomRecipeInstallationStore(room, TestClock(now)).readCatalog("corrupt.catalog") }116        }117    }118119    @Test120    fun explicitSourceRemovalAtomicallyRemovesOnlySelectedInstallAndPreservesTrustAndReplay() = runBlocking {121        withRoom { path, room ->122            val clock = TestClock(now)123            val store = RoomRecipeInstallationStore(room, clock)124            store.enrollIfAbsent(catalogId, policy())125            val first = store.readCatalog(catalogId)!!126            store.commitInstall(first.generation, candidate(first, 10, stableId = "selected"))127            val second = store.readCatalog(catalogId)!!128            store.commitInstall(second.generation, candidate(second, 11, stableId = "retained"))129            val before = store.readCatalog(catalogId)!!130            val selectedId = recipeSourceId(catalogId, "selected")131            val retainedId = recipeSourceId(catalogId, "retained")132            primeYokanDatabase(room)133            val database = RoomYokanDatabase(room)134            val replacement = database.snapshot().copy(sources = database.sources().filterNot { it.id == selectedId })135136            database.replaceAllAtomically(replacement, database.snapshot(), setOf(selectedId))137            assertEquals(listOf("retained"), store.readCatalog(catalogId)!!.installedRecords.keys.toList())138            room.close()139140            val reopened = openRoom(path)141            try {142                val restored = RoomRecipeInstallationStore(reopened, clock).readCatalog(catalogId)!!143                assertEquals(before.generation.value + 1, restored.generation.value)144                assertEquals(11, restored.acceptanceState!!.highestRevision)145                assertEquals(listOf("retained"), restored.installedRecords.keys.toList())146                assertEquals(before.trustPolicy.trustedKeys.single().rawEd25519PublicKey.toList(), restored.trustPolicy.trustedKeys.single().rawEd25519PublicKey.toList())147                assertNull(reopened.sourceDao().source(selectedId))148                assertEquals(retainedId, reopened.sourceDao().source(retainedId)?.id)149                assertEquals(seedDatabaseSnapshot().sources.map { it.id }.toSet() + retainedId, reopened.sourceDao().all().map { it.id }.toSet())150            } finally {151                reopened.close()152            }153        }154    }155156    @Test157    fun explicitSourceRemovalRollsBackInstallAndDelegateOnReplacementFailure() = runBlocking {158        withRoom { _, room ->159            val store = RoomRecipeInstallationStore(room, TestClock(now))160            store.enrollIfAbsent(catalogId, policy())161            val initial = store.readCatalog(catalogId)!!162            store.commitInstall(initial.generation, candidate(initial, 10))163            primeYokanDatabase(room)164            val database = RoomYokanDatabase(room)165            val before = database.snapshot()166            val sourceId = recipeSourceId(catalogId, "recipe.one")167            val replacement = before.copy(sources = before.sources.filterNot { it.id == sourceId })168            room.useWriterConnection { connection ->169                connection.usePrepared("CREATE TRIGGER fail_recipe_delete BEFORE DELETE ON recipe_catalog_installed BEGIN SELECT RAISE(ABORT, 'injected failure'); END") { it.step() }170            }171172            assertFailsWith<Exception> {173                database.replaceAllAtomically(replacement, before, setOf(sourceId))174            }175            assertEquals(before, database.snapshot())176            assertEquals(sourceId, room.sourceDao().source(sourceId)?.id)177            assertEquals(listOf("recipe.one"), store.readCatalog(catalogId)!!.installedRecords.keys.toList())178        }179    }180181    @Test182    fun explicitSourceRemovalRejectsConcurrentRecipeSourceInventoryChange() = runBlocking {183        withRoom { _, room ->184            val clock = TestClock(now)185            val store = RoomRecipeInstallationStore(room, clock)186            store.enrollIfAbsent(catalogId, policy())187            val initial = store.readCatalog(catalogId)!!188            store.commitInstall(initial.generation, candidate(initial, 10))189            primeYokanDatabase(room)190            val database = RoomYokanDatabase(room)191            val before = database.snapshot()192            val selectedId = recipeSourceId(catalogId, "recipe.one")193            val newer = store.readCatalog(catalogId)!!194            store.commitInstall(newer.generation, candidate(newer, 11, stableId = "concurrent"))195196            assertFailsWith<SnapshotReplacementConflictException> {197                database.replaceAllAtomically(before.copy(sources = before.sources.filterNot { it.id == selectedId }), before, setOf(selectedId))198            }199            assertEquals(before, database.snapshot())200            assertEquals(setOf("recipe.one", "concurrent"), store.readCatalog(catalogId)!!.installedRecords.keys)201        }202    }203204    private fun policy(validUntil: Long? = null): CatalogTrustPolicy = CatalogTrustPolicy(205        catalogId,206        listOf(TrustedCatalogKey(catalogId, "catalog-key", ByteArray(32) { 7 }, TrustedCatalogKeyState.Active, validUntilEpochSeconds = validUntil)),207    )208209    private fun candidate(210        snapshot: eu.friedcutlet.yokan.services.extensions.recipe.CatalogInstallationSnapshot,211        revision: Long,212        stableId: String = "recipe.one",213        artifact: ByteArray = byteArrayOf(1),214        release: String = "1",215        digest: String = "0".repeat(64),216    ): RecipeInstallCandidate = RecipeInstallCandidate(217        catalogId = catalogId,218        expectedTrustPolicy = snapshot.trustPolicy,219        expectedAcceptanceState = snapshot.acceptanceState,220        acceptedAcceptanceState = CatalogAcceptanceState(catalogId, revision, ByteArray(32) { revision.toByte() }),221        expiresAtEpochSeconds = now + 600,222        signingKeyId = "catalog-key",223        signingKeyValidFromEpochSeconds = null,224        signingKeyValidUntilEpochSeconds = snapshot.trustPolicy.trustedKeys.single().validUntilEpochSeconds,225        record = InstalledRecipeRecord(catalogId, stableId, revision, release, digest, artifact.size.toLong(), artifact),226    )227228    private fun openRoom(path: String): YokanRoomDatabase = Room.databaseBuilder<YokanRoomDatabase>(name = path).buildYokanRoom()229230    private suspend fun primeYokanDatabase(room: YokanRoomDatabase) {231        room.settingsDao().upsert(seedDatabaseSnapshot().settings.toRow())232    }233234    private fun createV5Fixture(path: String) {235        val schemaFile = listOf(236            File("schemas/eu.friedcutlet.yokan.database.room.YokanRoomDatabase/5.json"),237            File("composeApp/schemas/eu.friedcutlet.yokan.database.room.YokanRoomDatabase/5.json"),238        ).firstOrNull(File::isFile) ?: error("Missing checked-in Room v5 schema fixture")239        val schema = Json.parseToJsonElement(schemaFile.readText())240        val connection = BundledSQLiteDriver().open(path)241        try {242            val database = schema.jsonObject.getValue("database").jsonObject243            database.getValue("entities").jsonArray.forEach { entity ->244                val fields = entity.jsonObject245                connection.execSQL(fields.getValue("createSql").jsonPrimitive.content.replace("${'$'}{TABLE_NAME}", fields.getValue("tableName").jsonPrimitive.content))246            }247            connection.execSQL("CREATE TABLE room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)")248            connection.execSQL("INSERT INTO room_master_table (id,identity_hash) VALUES(42, 'c33259b810d394a8cdb715a794e18a5b')")249            connection.execSQL("PRAGMA user_version = 5")250            connection.execSQL("INSERT INTO manga (id, status, itemType, favorite, lastRead, isLocalArchive, updatedAt) VALUES(77, 'unknown', 'manga', 0, 0, 0, 0)")251        } finally {252            connection.close()253        }254    }255256    private suspend fun withRoom(block: suspend (String, YokanRoomDatabase) -> Unit) {257        val directory = Files.createTempDirectory("yokan-recipe-room")258        val path = directory.resolve("yokan.db").toString()259        val room = openRoom(path)260        try {261            block(path, room)262        } finally {263            runCatching { room.close() }264            directory.toFile().deleteRecursively()265        }266    }267268}269

Search chapters, reference and source filenames.