Yokan / rebuild
Course 1 8624561

RoomYokanDatabase.kt

composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/database/room/RoomYokanDatabase.kt

implementation740 lines
1package eu.friedcutlet.yokan.database.room23import androidx.room.Transactor4import androidx.room.useWriterConnection5import eu.friedcutlet.yokan.database.DbCategory6import eu.friedcutlet.yokan.database.DbChangedPart7import eu.friedcutlet.yokan.database.DbChapter8import eu.friedcutlet.yokan.database.DbChapterPageUrls9import eu.friedcutlet.yokan.database.DbCustomButton10import eu.friedcutlet.yokan.database.DbDownload11import eu.friedcutlet.yokan.database.DbHistory12import eu.friedcutlet.yokan.database.DbItemType13import eu.friedcutlet.yokan.database.DbManga14import eu.friedcutlet.yokan.database.DbOutboxOp15import eu.friedcutlet.yokan.database.DbSettings16import eu.friedcutlet.yokan.database.DbSource17import eu.friedcutlet.yokan.database.DbSyncPreference18import eu.friedcutlet.yokan.database.SyncServerProvider19import eu.friedcutlet.yokan.database.DbTrack20import eu.friedcutlet.yokan.database.DbTrackPreference21import eu.friedcutlet.yokan.database.DbTrackSearch22import eu.friedcutlet.yokan.database.DbUpdate23import eu.friedcutlet.yokan.database.InMemoryYokanDatabase24import eu.friedcutlet.yokan.database.SnapshotReplacementConflictException25import eu.friedcutlet.yokan.database.YokanDatabase26import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot27import eu.friedcutlet.yokan.database.seedDatabaseSnapshot28import eu.friedcutlet.yokan.database.withMangayomiLocalSyncTimestamps29import eu.friedcutlet.yokan.database.sync.hubResync30import eu.friedcutlet.yokan.database.sync.mangayomiDeleteParts31import eu.friedcutlet.yokan.services.extensions.recipe.recipeSourceId32import eu.friedcutlet.yokan.services.catchingNonCancellation33import eu.friedcutlet.yokan.services.logging.AppLogger34import eu.friedcutlet.yokan.util.PlatformLock35import eu.friedcutlet.yokan.util.nowMillis36import kotlinx.coroutines.CancellationException37import kotlinx.coroutines.CompletableDeferred38import kotlinx.coroutines.CoroutineScope39import kotlinx.coroutines.Job40import kotlinx.coroutines.NonCancellable41import kotlinx.coroutines.SupervisorJob42import kotlinx.coroutines.async43import kotlinx.coroutines.awaitAll44import kotlinx.coroutines.channels.Channel45import kotlinx.coroutines.coroutineScope46import kotlinx.coroutines.currentCoroutineContext47import kotlinx.coroutines.delay48import kotlinx.coroutines.ensureActive49import kotlinx.coroutines.flow.StateFlow50import kotlinx.coroutines.launch51import kotlinx.coroutines.runBlocking52import kotlinx.coroutines.withContext53import kotlinx.coroutines.withTimeout54import kotlinx.coroutines.cancelAndJoin55import kotlinx.coroutines.sync.Mutex56import kotlinx.coroutines.sync.withLock5758/**59 * Persists every `YokanDatabase` mutation through Room while keeping60 * `InMemoryYokanDatabase` as the synchronous read surface. This preserves61 * the existing `YokanDatabase` contract (synchronous, non-suspend methods)62 * across every call site in the app while replacing the old write-through63 * "serialize the whole JSON snapshot on every change" with "INSERT … ON64 * CONFLICT one row".65 *66 * Lifecycle:67 *   • Construction (synchronous) — block once on a Room load, hydrate the68 *     in-memory delegate from it. If Room is empty and a legacy JSON snapshot69 *     was provided, seed Room from that snapshot in the background.70 *   • Mutations — apply to the in-memory delegate first (so reads see the71 *     change immediately), then enqueue a Room write on a dedicated scope.72 *     The queue is ordered so deletes/updates are applied serially, and the73 *     worker commits everything queued since its last commit in one74 *     transaction instead of one per row. Enqueueing never blocks.75 *   • Hub outbox — every synced write may append ops to the delegate's76 *     outbox; the rows added by one mutation are persisted in the same77 *     queued action as the row itself.78 *79 * Why a write queue instead of suspending API: every existing call site of80 * `YokanDatabase` is non-suspend. Threading suspend through the codebase is81 * a much larger change; queueing keeps Room writes off the calling thread82 * without changing the contract.83 */84class RoomYokanDatabase(85    internal val room: YokanRoomDatabase,86    legacySnapshotProvider: () -> YokanDatabaseSnapshot? = { null },87    private val closeTimeoutMillis: Long = 15_000,88) : YokanDatabase {89    private val scope = CoroutineScope(roomPersistenceDispatcher + SupervisorJob())90    // ponytail: unbounded, so no caller (the UI thread included) ever blocks on a full queue; the91    // backlog only grows while Room keeps failing. Bound it once the API can suspend.92    private val writes = Channel<QueuedWrite>(Channel.UNLIMITED)93    private val batchLock = PlatformLock()94    private val batchedWrites = mutableListOf<suspend () -> Unit>()95    private var persistenceBatchDepth = 096    private var remoteApplyDepth = 097    private val startupReady = CompletableDeferred<Unit>()98    private val delegate: InMemoryYokanDatabase99    private val retirementLock = Mutex()100    private var acceptingWrites = true // guarded by batchLock101    private var queueClosed = false102    private var closed = false103    private val worker: Job104105    init {106        require(closeTimeoutMillis > 0)107        // Synchronous hydrate so YokanDatabase callers see a fully-formed108        // snapshot on the first call. Blocks the bootstrap thread once, off109        // the UI thread, on the same dedicated dispatcher used by Room.110        val hydrated = runBlocking(roomPersistenceDispatcher) { readAllFromRoom() }111        val initial = when {112            hydrated != null -> hydrated113            else -> {114                // Cold Room — invoke the legacy JSON provider only now. On115                // every subsequent boot Room has data so this allocator116                // never runs and the JSON file is never read.117                val legacy = legacySnapshotProvider()118                if (legacy != null) {119                    legacy120                } else {121                    seedDatabaseSnapshot()122                }123            }124        }125        delegate = InMemoryYokanDatabase(initial)126127        // Persist the initial seed or imported legacy snapshot when Room is empty.128        if (hydrated == null) {129            val seed = delegate.snapshot()130            scope.launch {131                // A failed first import must not make a later flush look successful.132                retrying { importSnapshot(seed) }133                startupReady.complete(Unit)134            }135        } else {136            // The delegate dropped the epoch-0 ops no hub accepts; drop them from Room as well.137            if (delegate.outbox().size < hydrated.outbox.size) enqueue { room.outboxDao().clearUnnegotiated() }138            startupReady.complete(Unit)139        }140141        // Write worker — serial execution preserves causal ordering so a142        // delete that follows an upsert can't race ahead.143        worker = scope.launch {144            startupReady.await()145            val pending = ArrayList<suspend () -> Unit>()146            for (first in writes) {147                var write: QueuedWrite? = first148                while (write != null) {149                    if (write.coalesce) {150                        pending += write.action151                    } else {152                        commit(pending)153                        retrying(write.action)154                    }155                    write = writes.tryReceive().getOrNull()156                }157                commit(pending)158            }159        }160    }161162    // ── reads (pass-through) ────────────────────────────────────────────────163    override fun snapshot(): YokanDatabaseSnapshot = delegate.snapshot()164    override fun snapshots(): StateFlow<YokanDatabaseSnapshot> = delegate.snapshots()165166    override fun supportsAtomicSnapshotPersistence(): Boolean = true167168    override suspend fun awaitPersistence() {169        val completion = CompletableDeferred<Unit>()170        batchLock.withLock {171            check(!queueClosed) { "Room write queue is closed" }172            enqueue(coalesce = false) {173                inTransaction { }174                completion.complete(Unit)175            }176        }177        // A flush is cancellable, unlike a mutation whose transaction must be joined.178        // Its harmless queued barrier remains ordered if the caller times out.179        completion.await()180    }181182    override suspend fun close() = retirementLock.withLock {183        if (closed) return@withLock184        withContext(NonCancellable) {185            batchLock.withLock { acceptingWrites = false }186            try {187                if (!queueClosed) {188                    withTimeout(closeTimeoutMillis) {189                        awaitPersistence()190                        batchLock.withLock { writes.close(); queueClosed = true }191                        worker.join()192                    }193                }194                scope.coroutineContext[Job]?.cancelAndJoin()195                room.close()196                closed = true197            } catch (error: Throwable) {198                // Before channel closure, leave both pending writes and the live database usable.199                if (!queueClosed) batchLock.withLock { acceptingWrites = true }200                throw error201            }202        }203    }204205    override suspend fun replaceAllAtomically(206        snapshot: YokanDatabaseSnapshot,207        expectedSnapshot: YokanDatabaseSnapshot?,208        removedSourceIds: Set<Long>,209    ) {210        val callerJob = currentCoroutineContext()[Job]211        batchLock.withLock {212            check(persistenceBatchDepth == 0) { "Snapshot replacement cannot run inside a mutation batch" }213            check(remoteApplyDepth == 0) { "Snapshot replacement cannot run inside remote apply" }214            callerJob?.ensureActive()215        }216        // Do not block the serialized Room lane while waiting for its queued217        // transaction to complete.218        withContext(roomReplacementDispatcher) {219            replaceAllSynchronously(snapshot, expectedSnapshot, callerJob, removedSourceIds)220        }221    }222223    override suspend fun replaceAllRemoteAtomically(snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot?) {224        val callerJob = currentCoroutineContext()[Job]225        batchLock.withLock {226            check(persistenceBatchDepth == 0) { "Snapshot replacement cannot run inside a mutation batch" }227            callerJob?.ensureActive()228        }229        withContext(roomReplacementDispatcher) {230            replaceAllSynchronously(snapshot, expectedSnapshot, callerJob, remoteApply = true)231        }232    }233    override fun settings(): DbSettings = delegate.settings()234    override fun mangas(itemType: DbItemType?) = delegate.mangas(itemType)235    override fun manga(id: Long) = delegate.manga(id)236    override fun chapters(mangaId: Long?) = delegate.chapters(mangaId)237    override fun chapter(id: Long) = delegate.chapter(id)238    override fun categories(itemType: DbItemType?) = delegate.categories(itemType)239    override fun sources(itemType: DbItemType?) = delegate.sources(itemType)240    override fun source(id: Long) = delegate.source(id)241    override fun histories() = delegate.histories()242    override fun updates() = delegate.updates()243    override fun downloads() = delegate.downloads()244    override fun download(id: Long) = delegate.download(id)245    override fun tracks(mangaId: Long?) = delegate.tracks(mangaId)246    override fun trackPreferences() = delegate.trackPreferences()247    override fun trackSearches(syncId: Int?) = delegate.trackSearches(syncId)248    override fun syncPreferences() = delegate.syncPreferences()249    override fun changedParts() = delegate.changedParts()250    override fun customButtons() = delegate.customButtons()251    override fun pageCache(chapterId: Long?) = delegate.pageCache(chapterId)252    override fun outbox() = delegate.outbox()253254    // ── writes (in-memory + Room queue) ─────────────────────────────────────255    override fun updateSettings(settings: DbSettings) = tracked({ delegate.updateSettings(settings) }) {256        room.settingsDao().upsert(settings.toRow())257    }258259    override fun replaceAll(260        snapshot: YokanDatabaseSnapshot,261        expectedSnapshot: YokanDatabaseSnapshot?,262    ) = replaceAllSynchronously(snapshot, expectedSnapshot, null)263264    override fun upsertManga(manga: DbManga): DbManga = batchLock.withLock {265        val previousCast = delegate.manga(manga.id)?.cast266        tracked({ delegate.upsertManga(manga) }) { saved ->267            room.mangaDao().upsert(saved.toRow())268            if (previousCast != saved.cast) {269                room.mangaCreditDao().deleteForManga(saved.id)270                if (saved.cast.isNotEmpty()) room.mangaCreditDao().upsertAll(saved.toCreditRows())271            }272        }273    }274275    override fun removeManga(id: Long, recordChange: Boolean) = tracked({ delegate.removeManga(id, recordChange) }) {276        room.mangaDao().delete(id)277    }278279    override fun upsertChapter(chapter: DbChapter): DbChapter = tracked({ delegate.upsertChapter(chapter) }) { saved ->280        room.chapterDao().upsert(saved.toRow())281    }282283    override fun removeChapter(id: Long, recordChange: Boolean) = tracked({ delegate.removeChapter(id, recordChange) }) {284        room.chapterDao().delete(id)285        room.pageCacheDao().delete(id)286    }287288    override fun upsertCategory(category: DbCategory): DbCategory = tracked({ delegate.upsertCategory(category) }) { saved ->289        room.categoryDao().upsert(saved.toRow())290    }291292    override fun removeCategory(id: Long, recordChange: Boolean) = tracked({ delegate.removeCategory(id, recordChange) }) {293        room.categoryDao().delete(id)294    }295296    override fun upsertSource(source: DbSource): DbSource {297        return mutate({ delegate.upsertSource(source) }) { saved ->298            room.sourceDao().upsert(saved.toRow())299        }300    }301302    override fun removeSource(id: Long) {303        mutate({ delegate.removeSource(id) }) { room.sourceDao().delete(id) }304    }305306    override fun upsertHistory(history: DbHistory): DbHistory = tracked({ delegate.upsertHistory(history) }) { saved ->307        room.historyDao().upsert(saved.toRow())308    }309310    override fun removeHistory(id: Long, recordChange: Boolean) = tracked({ delegate.removeHistory(id, recordChange) }) {311        room.historyDao().delete(id)312    }313314    override fun upsertUpdate(update: DbUpdate): DbUpdate = tracked({ delegate.upsertUpdate(update) }) { saved ->315        room.updateDao().upsert(saved.toRow())316    }317318    override fun removeUpdate(id: Long, recordChange: Boolean) = tracked({ delegate.removeUpdate(id, recordChange) }) {319        room.updateDao().delete(id)320    }321322    override fun upsertDownload(download: DbDownload): DbDownload {323        return mutate({ delegate.upsertDownload(download) }) { saved ->324            room.downloadDao().upsert(saved.toRow())325        }326    }327328    override fun removeDownload(id: Long) {329        mutate({ delegate.removeDownload(id) }) { room.downloadDao().delete(id) }330    }331332    override fun upsertTrack(track: DbTrack): DbTrack = tracked({ delegate.upsertTrack(track) }) { saved ->333        room.trackDao().upsert(saved.toRow())334    }335336    override fun removeTrack(id: Long, recordChange: Boolean) = tracked({ delegate.removeTrack(id, recordChange) }) {337        room.trackDao().delete(id)338    }339340    override fun upsertTrackPreference(preference: DbTrackPreference): DbTrackPreference {341        return mutate({ delegate.upsertTrackPreference(preference) }) { saved ->342            room.trackPreferenceDao().upsert(saved.toRow())343        }344    }345346    override fun upsertTrackSearch(search: DbTrackSearch): DbTrackSearch {347        return mutate({ delegate.upsertTrackSearch(search) }) { saved ->348            room.trackSearchDao().upsert(saved.toRow())349        }350    }351352    override fun upsertSyncPreference(preference: DbSyncPreference): DbSyncPreference {353        return mutate({ delegate.upsertSyncPreference(preference) }) { saved ->354            room.syncPreferenceDao().upsert(saved.toRow())355        }356    }357358    override suspend fun upsertSyncPreferenceIf(359        syncId: Long,360        accepts: (DbSyncPreference?) -> Boolean,361        transform: (DbSyncPreference?) -> DbSyncPreference,362    ): Boolean {363        val accepted = batchLock.withLock {364            check(acceptingWrites) { "Room database is retiring or closed" }365            val current = delegate.syncPreferences().firstOrNull { it.syncId == syncId }366            if (!accepts(current)) return@withLock false367            val updated = delegate.upsertSyncPreference(transform(current).copy(syncId = syncId))368            queueWrite { room.syncPreferenceDao().upsert(updated.toRow()) }369            true370        }371        if (accepted) withContext(NonCancellable) { awaitPersistence() }372        return accepted373    }374375    override fun recordChange(change: DbChangedPart): DbChangedPart {376        return mutate({ delegate.recordChange(change) }) { saved ->377            room.changedPartDao().upsert(saved.toRow())378        }379    }380381    override fun clearChangedParts() {382        mutate({ delegate.clearChangedParts() }) { room.changedPartDao().clear() }383    }384385    override fun upsertCustomButton(button: DbCustomButton): DbCustomButton {386        return mutate({ delegate.upsertCustomButton(button) }) { saved ->387            room.customButtonDao().upsert(saved.toRow())388        }389    }390391    override fun removeCustomButton(id: Long) {392        mutate({ delegate.removeCustomButton(id) }) { room.customButtonDao().delete(id) }393    }394395    override fun upsertPageCache(cache: DbChapterPageUrls): DbChapterPageUrls = batchLock.withLock {396        check(acceptingWrites) { "Room database is retiring or closed" }397        val before = delegate.pageCache().mapNotNullTo(HashSet()) { it.chapterId }398        val saved = delegate.upsertPageCache(cache)399        val evicted = before - delegate.pageCache().mapNotNullTo(HashSet()) { it.chapterId }400        queueWrite {401            room.pageCacheDao().upsert(saved.toRow())402            evicted.forEach { room.pageCacheDao().delete(it) }403        }404        saved405    }406407    override fun removePageCache(chapterIds: Collection<Long>) {408        val ids = chapterIds.toList()409        if (ids.isEmpty()) return410        mutate({ delegate.removePageCache(ids) }) { ids.forEach { room.pageCacheDao().delete(it) } }411    }412413    override fun clearPageCache() {414        mutate({ delegate.clearPageCache() }) { room.pageCacheDao().clear() }415    }416417    // ── hub sync ────────────────────────────────────────────────────────────418    override fun removeOutbox(ops: List<DbOutboxOp>) {419        mutate({ delegate.removeOutbox(ops) }) {420            ops.forEach { room.outboxDao().deleteIfUnchanged(it.kind, it.id, it.path, it.seq) }421        }422    }423424    override suspend fun resyncHub(syncId: Long, epoch: Int): DbSyncPreference {425        val updated = batchLock.withLock {426            check(acceptingWrites) { "Room database is retiring or closed" }427            val current = delegate.syncPreferences().firstOrNull { it.syncId == syncId }428                ?: DbSyncPreference(syncId = syncId)429            val (resynced, dropBefore) = current.hubResync(epoch)430            val stale = dropBefore?.let { floor -> delegate.outbox().filter { it.epoch < floor } }.orEmpty()431            val updated = delegate.batch {432                delegate.removeOutbox(stale)433                delegate.upsertSyncPreference(resynced)434            }435            // Queued under the lock so no later write to the same rows can overtake it.436            queueWrite {437                room.syncPreferenceDao().upsert(updated.toRow())438                stale.forEach { room.outboxDao().deleteIfUnchanged(it.kind, it.id, it.path, it.seq) }439            }440            updated441        }442        withContext(NonCancellable) { awaitPersistence() }443        return updated444    }445446    override fun <T> applyRemote(block: () -> T): T = batchLock.withLock {447        check(acceptingWrites) { "Room database is retiring or closed" }448        remoteApplyDepth++449        try {450            delegate.applyRemote(block)451        } finally {452            remoteApplyDepth--453        }454    }455456    override fun <T> batch(block: () -> T): T = batchLock.withLock {457        check(acceptingWrites) { "Room database is retiring or closed" }458        persistenceBatchDepth++459        try {460            delegate.batch(block)461        } finally {462            persistenceBatchDepth--463            if (persistenceBatchDepth == 0 && batchedWrites.isNotEmpty()) {464                val batched = batchedWrites.toList()465                batchedWrites.clear()466                // One queued action, so the whole batch always lands in the same transaction.467                enqueue { batched.forEach { it() } }468            }469        }470    }471472    /**473     * Run a synced mutation on the delegate, then queue its Room row write together with474     * whatever outbox ops the mutation appended.475     */476    private inline fun <T> tracked(crossinline mutation: () -> T, crossinline persist: suspend (T) -> Unit): T =477        batchLock.withLock {478            check(acceptingWrites) { "Room database is retiring or closed" }479            val oldChangedIds = delegate.changedParts().mapTo(HashSet(), DbChangedPart::id)480            val (result, ops) = delegate.recordingOutbox { mutation() }481            val rows = ops.map { it.toRow() }482            val changedRows = delegate.changedParts().filter { it.id !in oldChangedIds }.map { it.toRow() }483            queueWrite {484                persist(result)485                if (rows.isNotEmpty()) room.outboxDao().upsertAll(rows)486                if (changedRows.isNotEmpty()) room.changedPartDao().upsertAll(changedRows)487            }488            result489        }490491    private inline fun <T> mutate(crossinline mutation: () -> T, crossinline persist: suspend (T) -> Unit): T =492        batchLock.withLock {493            check(acceptingWrites) { "Room database is retiring or closed" }494            val result = mutation()495            queueWrite { persist(result) }496            result497        }498499    private fun queueWrite(action: suspend () -> Unit) {500        batchLock.withLock {501            if (persistenceBatchDepth > 0) batchedWrites += action else enqueue(action = action)502        }503    }504505    /** [coalesce]d writes share the worker's next transaction; others bring their own. */506    private fun enqueue(coalesce: Boolean = true, action: suspend () -> Unit) {507        check(writes.trySend(QueuedWrite(coalesce, action)).isSuccess) { "Room write queue is closed" }508    }509510    /** Run [action] in its own transaction once everything queued before it is committed. */511    private suspend fun enqueueAndAwait(action: suspend () -> Unit) {512        val completion = CompletableDeferred<Unit>()513        enqueue(coalesce = false) {514            try {515                inTransaction(action)516                completion.complete(Unit)517            } catch (error: Throwable) {518                // Always release the blocked caller, but let cancellation keep propagating.519                completion.completeExceptionally(error)520                if (error is CancellationException) throw error521            }522        }523        withContext(NonCancellable) { completion.await() }524    }525526    private suspend fun commit(pending: MutableList<suspend () -> Unit>) {527        if (pending.isEmpty()) return528        val actions = pending.toList()529        pending.clear()530        retrying { inTransaction { actions.forEach { it() } } }531    }532533    private suspend fun retrying(write: suspend () -> Unit) {534        var attempt = 0535        while (true) {536            try {537                write()538                return539            } catch (error: Throwable) {540                if (error is CancellationException) throw error541                attempt++542                AppLogger.error("[room] write failed (attempt $attempt; retrying): ${error.message.orEmpty()}")543                delay((50L shl attempt.coerceAtMost(6)).coerceAtMost(MAX_WRITE_RETRY_DELAY_MS))544            }545        }546    }547548    private suspend fun inTransaction(block: suspend () -> Unit) {549        room.useWriterConnection { connection ->550            connection.withTransaction(Transactor.SQLiteTransactionType.IMMEDIATE) { block() }551        }552    }553554    private fun replaceAllSynchronously(555        snapshot: YokanDatabaseSnapshot,556        expectedSnapshot: YokanDatabaseSnapshot?,557        callerJob: Job?,558        removedSourceIds: Set<Long> = emptySet(),559        remoteApply: Boolean = false,560    ) = batchLock.withLock {561        check(acceptingWrites) { "Room database is retiring or closed" }562        check(persistenceBatchDepth == 0) { "Snapshot replacement cannot run inside a mutation batch" }563        check(remoteApplyDepth == 0) { "Snapshot replacement cannot run inside remote apply" }564        callerJob?.ensureActive()565        if (expectedSnapshot != null && delegate.snapshot() != expectedSnapshot) {566            throw SnapshotReplacementConflictException()567        }568        val expectedSourceIds = delegate.sources().mapTo(HashSet(), DbSource::id)569        if (removedSourceIds.isNotEmpty() &&570            (!expectedSourceIds.containsAll(removedSourceIds) || snapshot.sources.any { it.id in removedSourceIds })571        ) {572            throw SnapshotReplacementConflictException()573        }574        val target = if (remoteApply) snapshot else snapshot.withMangayomiLocalSyncTimestamps(delegate.snapshot()).withMangayomiDeletes(delegate.snapshot())575        // Blocks by contract: the snapshot is published only after Room committed it. The576        // suspending replaceAllAtomically runs this on roomReplacementDispatcher instead.577        runBlocking {578            enqueueAndAwait {579                if (removedSourceIds.isNotEmpty()) {580                    removeRecipeInstallations(removedSourceIds, expectedSourceIds)581                }582                writeAllTables(target, clearFirst = true)583            }584        }585        delegate.applyRemote { delegate.replaceAll(target) }586    }587588    private suspend fun removeRecipeInstallations(removedSourceIds: Set<Long>, expectedSourceIds: Set<Long>) {589        val actualSourceIds = room.sourceDao().all().mapTo(HashSet()) { it.id }590        if (actualSourceIds != expectedSourceIds) throw SnapshotReplacementConflictException()591592        val installationDao = room.recipeInstallationDao()593        val affected = installationDao.allInstalled().filter { row ->594            if (row.catalogId.isBlank() || row.stableId.isBlank() || row.catalogRevision < 0) {595                throw IllegalStateException("Corrupt recipe installation")596            }597            val expectedId = recipeSourceId(row.catalogId, row.stableId)598            if (row.sourceId != null && row.sourceId != expectedId) {599                throw IllegalStateException("Corrupt recipe source association")600            }601            (row.sourceId ?: expectedId) in removedSourceIds602        }603        val byCatalog = affected.groupBy { it.catalogId }604        for ((catalogId, rows) in byCatalog) {605            val checkpoint = installationDao.checkpoint(catalogId)606                ?: throw IllegalStateException("Corrupt recipe catalog checkpoint")607            if (checkpoint.catalogId != catalogId || checkpoint.generation < 0) {608                throw IllegalStateException("Corrupt recipe catalog checkpoint")609            }610            if (checkpoint.generation == Long.MAX_VALUE) {611                throw IllegalStateException("Recipe catalog generation overflow")612            }613            rows.forEach { installationDao.deleteInstalled(it.catalogId, it.stableId) }614            installationDao.upsertCheckpoint(checkpoint.copy(generation = checkpoint.generation + 1))615        }616    }617618    private suspend fun readAllFromRoom(): YokanDatabaseSnapshot? = coroutineScope {619        // Fan-out every table read on the dedicated Room dispatcher. SQLite620        // serializes statements internally, and this view also orders the621        // worker's writes, hydration, and startup import.622        val mangasJob = async {623            val credits = room.mangaCreditDao().all().groupBy({ it.mangaId }, { it.toCredit() })624            room.mangaDao().all().map { it.toDb().copy(cast = credits[it.id].orEmpty()) }625        }626        val chaptersJob = async { room.chapterDao().all().map(ChapterRow::toDb) }627        val categoriesJob = async { room.categoryDao().all().map(CategoryRow::toDb) }628        val sourcesJob = async { room.sourceDao().all().map(SourceRow::toDb) }629        val historiesJob = async { room.historyDao().all().map(HistoryRow::toDb) }630        val updatesJob = async { room.updateDao().all().map(UpdateRow::toDb) }631        val downloadsJob = async { room.downloadDao().all().map(DownloadRow::toDb) }632        val tracksJob = async { room.trackDao().all().map(TrackRow::toDb) }633        val trackPrefsJob = async { room.trackPreferenceDao().all().map(TrackPreferenceRow::toDb) }634        val trackSearchesJob = async { room.trackSearchDao().all().map(TrackSearchRow::toDb) }635        val syncPrefsJob = async { room.syncPreferenceDao().all().map(SyncPreferenceRow::toDb) }636        val changedPartsJob = async { room.changedPartDao().all().map(ChangedPartRow::toDb) }637        val customButtonsJob = async { room.customButtonDao().all().map(CustomButtonRow::toDb) }638        val pageCacheJob = async { room.pageCacheDao().all().map(PageCacheRow::toDb) }639        val outboxJob = async { room.outboxDao().all().map(OutboxRow::toDb) }640        val settingsJob = async { room.settingsDao().get() }641642        // awaitAll on each list one at a time to keep the structured-concurrency643        // surface tidy and let the JIT cache the Db* mappers.644        val mangas = mangasJob.await()645        val chapters = chaptersJob.await()646        val settingsRow = settingsJob.await()647        // Treat an empty Room (no rows AND no settings blob) as "first648        // launch" so the caller can seed from the legacy JSON snapshot.649        if (settingsRow == null && mangas.isEmpty() && chapters.isEmpty()) {650            awaitAll(651                categoriesJob, sourcesJob, historiesJob, updatesJob, downloadsJob,652                tracksJob, trackPrefsJob, trackSearchesJob, syncPrefsJob,653                changedPartsJob, customButtonsJob, pageCacheJob, outboxJob,654            )655            return@coroutineScope null656        }657        YokanDatabaseSnapshot(658            settings = settingsRow?.toDb() ?: DbSettings(),659            mangas = mangas,660            chapters = chapters,661            categories = categoriesJob.await(),662            sources = sourcesJob.await(),663            histories = historiesJob.await(),664            updates = updatesJob.await(),665            downloads = downloadsJob.await(),666            tracks = tracksJob.await(),667            trackPreferences = trackPrefsJob.await(),668            trackSearches = trackSearchesJob.await(),669            syncPreferences = syncPrefsJob.await(),670            changedParts = changedPartsJob.await(),671            customButtons = customButtonsJob.await(),672            pageCache = pageCacheJob.await(),673            outbox = outboxJob.await(),674        )675    }676677    private suspend fun writeAllTables(snapshot: YokanDatabaseSnapshot, clearFirst: Boolean) {678        room.settingsDao().upsert(snapshot.settings.toRow())679        if (clearFirst) {680            room.mangaCreditDao().clear()681            room.mangaDao().clear()682            room.chapterDao().clear()683            room.categoryDao().clear()684            room.sourceDao().clear()685            room.historyDao().clear()686            room.updateDao().clear()687            room.downloadDao().clear()688            room.trackDao().clear()689            room.trackPreferenceDao().clear()690            room.trackSearchDao().clear()691            room.syncPreferenceDao().clear()692            room.changedPartDao().clear()693            room.customButtonDao().clear()694            room.pageCacheDao().clear()695            room.outboxDao().clear()696        }697        room.mangaDao().upsertAll(snapshot.mangas.map { it.toRow() })698        room.mangaCreditDao().upsertAll(snapshot.mangas.flatMap { it.toCreditRows() })699        room.chapterDao().upsertAll(snapshot.chapters.map { it.toRow() })700        room.categoryDao().upsertAll(snapshot.categories.map { it.toRow() })701        room.sourceDao().upsertAll(snapshot.sources.map { it.toRow() })702        room.historyDao().upsertAll(snapshot.histories.map { it.toRow() })703        room.updateDao().upsertAll(snapshot.updates.map { it.toRow() })704        room.downloadDao().upsertAll(snapshot.downloads.map { it.toRow() })705        room.trackDao().upsertAll(snapshot.tracks.map { it.toRow() })706        room.trackPreferenceDao().upsertAll(snapshot.trackPreferences.map { it.toRow() })707        room.trackSearchDao().upsertAll(snapshot.trackSearches.map { it.toRow() })708        room.syncPreferenceDao().upsertAll(snapshot.syncPreferences.map { it.toRow() })709        room.changedPartDao().upsertAll(snapshot.changedParts.map { it.toRow() })710        room.customButtonDao().upsertAll(snapshot.customButtons.map { it.toRow() })711        room.pageCacheDao().upsertAll(snapshot.pageCache.map { it.toRow() })712        room.outboxDao().upsertAll(snapshot.outbox.map { it.toRow() })713    }714715    private suspend fun importSnapshot(snapshot: YokanDatabaseSnapshot) {716        // Only runs against a cold (empty) Room, so no clears needed.717        room.useWriterConnection { connection ->718            connection.withTransaction(Transactor.SQLiteTransactionType.IMMEDIATE) {719                writeAllTables(snapshot, clearFirst = false)720            }721        }722        AppLogger.info(723            "[room] hydrated initial snapshot: " +724                "mangas=${snapshot.mangas.size} chapters=${snapshot.chapters.size} " +725                "histories=${snapshot.histories.size}",726        )727    }728729    /** A queued Room write; [coalesce]d writes run inside one shared transaction. */730    private class QueuedWrite(val coalesce: Boolean, val action: suspend () -> Unit)731732    private companion object {733        const val MAX_WRITE_RETRY_DELAY_MS = 5_000L734    }735}736737private fun YokanDatabaseSnapshot.withMangayomiDeletes(before: YokanDatabaseSnapshot): YokanDatabaseSnapshot {738    val additions = mangayomiDeleteParts(before, this, changedParts, nowMillis())739    return if (additions.isEmpty()) this else copy(changedParts = changedParts + additions)740}741

Search chapters, reference and source filenames.