package eu.friedcutlet.yokan.database.room import androidx.room.Transactor import androidx.room.useWriterConnection import eu.friedcutlet.yokan.database.DbCategory import eu.friedcutlet.yokan.database.DbChangedPart import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbChapterPageUrls import eu.friedcutlet.yokan.database.DbCustomButton import eu.friedcutlet.yokan.database.DbDownload import eu.friedcutlet.yokan.database.DbHistory import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbOutboxOp import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.database.SyncServerProvider import eu.friedcutlet.yokan.database.DbTrack import eu.friedcutlet.yokan.database.DbTrackPreference import eu.friedcutlet.yokan.database.DbTrackSearch import eu.friedcutlet.yokan.database.DbUpdate import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.SnapshotReplacementConflictException import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot import eu.friedcutlet.yokan.database.seedDatabaseSnapshot import eu.friedcutlet.yokan.database.withMangayomiLocalSyncTimestamps import eu.friedcutlet.yokan.database.sync.hubResync import eu.friedcutlet.yokan.database.sync.mangayomiDeleteParts import eu.friedcutlet.yokan.services.extensions.recipe.recipeSourceId import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.util.PlatformLock import eu.friedcutlet.yokan.util.nowMillis import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock /** * Persists every `YokanDatabase` mutation through Room while keeping * `InMemoryYokanDatabase` as the synchronous read surface. This preserves * the existing `YokanDatabase` contract (synchronous, non-suspend methods) * across every call site in the app while replacing the old write-through * "serialize the whole JSON snapshot on every change" with "INSERT … ON * CONFLICT one row". * * Lifecycle: * • Construction (synchronous) — block once on a Room load, hydrate the * in-memory delegate from it. If Room is empty and a legacy JSON snapshot * was provided, seed Room from that snapshot in the background. * • Mutations — apply to the in-memory delegate first (so reads see the * change immediately), then enqueue a Room write on a dedicated scope. * The queue is ordered so deletes/updates are applied serially, and the * worker commits everything queued since its last commit in one * transaction instead of one per row. Enqueueing never blocks. * • Hub outbox — every synced write may append ops to the delegate's * outbox; the rows added by one mutation are persisted in the same * queued action as the row itself. * * Why a write queue instead of suspending API: every existing call site of * `YokanDatabase` is non-suspend. Threading suspend through the codebase is * a much larger change; queueing keeps Room writes off the calling thread * without changing the contract. */ class RoomYokanDatabase( internal val room: YokanRoomDatabase, legacySnapshotProvider: () -> YokanDatabaseSnapshot? = { null }, private val closeTimeoutMillis: Long = 15_000, ) : YokanDatabase { private val scope = CoroutineScope(roomPersistenceDispatcher + SupervisorJob()) // ponytail: unbounded, so no caller (the UI thread included) ever blocks on a full queue; the // backlog only grows while Room keeps failing. Bound it once the API can suspend. private val writes = Channel(Channel.UNLIMITED) private val batchLock = PlatformLock() private val batchedWrites = mutableListOf Unit>() private var persistenceBatchDepth = 0 private var remoteApplyDepth = 0 private val startupReady = CompletableDeferred() private val delegate: InMemoryYokanDatabase private val retirementLock = Mutex() private var acceptingWrites = true // guarded by batchLock private var queueClosed = false private var closed = false private val worker: Job init { require(closeTimeoutMillis > 0) // Synchronous hydrate so YokanDatabase callers see a fully-formed // snapshot on the first call. Blocks the bootstrap thread once, off // the UI thread, on the same dedicated dispatcher used by Room. val hydrated = runBlocking(roomPersistenceDispatcher) { readAllFromRoom() } val initial = when { hydrated != null -> hydrated else -> { // Cold Room — invoke the legacy JSON provider only now. On // every subsequent boot Room has data so this allocator // never runs and the JSON file is never read. val legacy = legacySnapshotProvider() if (legacy != null) { legacy } else { seedDatabaseSnapshot() } } } delegate = InMemoryYokanDatabase(initial) // Persist the initial seed or imported legacy snapshot when Room is empty. if (hydrated == null) { val seed = delegate.snapshot() scope.launch { // A failed first import must not make a later flush look successful. retrying { importSnapshot(seed) } startupReady.complete(Unit) } } else { // The delegate dropped the epoch-0 ops no hub accepts; drop them from Room as well. if (delegate.outbox().size < hydrated.outbox.size) enqueue { room.outboxDao().clearUnnegotiated() } startupReady.complete(Unit) } // Write worker — serial execution preserves causal ordering so a // delete that follows an upsert can't race ahead. worker = scope.launch { startupReady.await() val pending = ArrayList Unit>() for (first in writes) { var write: QueuedWrite? = first while (write != null) { if (write.coalesce) { pending += write.action } else { commit(pending) retrying(write.action) } write = writes.tryReceive().getOrNull() } commit(pending) } } } // ── reads (pass-through) ──────────────────────────────────────────────── override fun snapshot(): YokanDatabaseSnapshot = delegate.snapshot() override fun snapshots(): StateFlow = delegate.snapshots() override fun supportsAtomicSnapshotPersistence(): Boolean = true override suspend fun awaitPersistence() { val completion = CompletableDeferred() batchLock.withLock { check(!queueClosed) { "Room write queue is closed" } enqueue(coalesce = false) { inTransaction { } completion.complete(Unit) } } // A flush is cancellable, unlike a mutation whose transaction must be joined. // Its harmless queued barrier remains ordered if the caller times out. completion.await() } override suspend fun close() = retirementLock.withLock { if (closed) return@withLock withContext(NonCancellable) { batchLock.withLock { acceptingWrites = false } try { if (!queueClosed) { withTimeout(closeTimeoutMillis) { awaitPersistence() batchLock.withLock { writes.close(); queueClosed = true } worker.join() } } scope.coroutineContext[Job]?.cancelAndJoin() room.close() closed = true } catch (error: Throwable) { // Before channel closure, leave both pending writes and the live database usable. if (!queueClosed) batchLock.withLock { acceptingWrites = true } throw error } } } override suspend fun replaceAllAtomically( snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot?, removedSourceIds: Set, ) { val callerJob = currentCoroutineContext()[Job] batchLock.withLock { check(persistenceBatchDepth == 0) { "Snapshot replacement cannot run inside a mutation batch" } check(remoteApplyDepth == 0) { "Snapshot replacement cannot run inside remote apply" } callerJob?.ensureActive() } // Do not block the serialized Room lane while waiting for its queued // transaction to complete. withContext(roomReplacementDispatcher) { replaceAllSynchronously(snapshot, expectedSnapshot, callerJob, removedSourceIds) } } override suspend fun replaceAllRemoteAtomically(snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot?) { val callerJob = currentCoroutineContext()[Job] batchLock.withLock { check(persistenceBatchDepth == 0) { "Snapshot replacement cannot run inside a mutation batch" } callerJob?.ensureActive() } withContext(roomReplacementDispatcher) { replaceAllSynchronously(snapshot, expectedSnapshot, callerJob, remoteApply = true) } } override fun settings(): DbSettings = delegate.settings() override fun mangas(itemType: DbItemType?) = delegate.mangas(itemType) override fun manga(id: Long) = delegate.manga(id) override fun chapters(mangaId: Long?) = delegate.chapters(mangaId) override fun chapter(id: Long) = delegate.chapter(id) override fun categories(itemType: DbItemType?) = delegate.categories(itemType) override fun sources(itemType: DbItemType?) = delegate.sources(itemType) override fun source(id: Long) = delegate.source(id) override fun histories() = delegate.histories() override fun updates() = delegate.updates() override fun downloads() = delegate.downloads() override fun download(id: Long) = delegate.download(id) override fun tracks(mangaId: Long?) = delegate.tracks(mangaId) override fun trackPreferences() = delegate.trackPreferences() override fun trackSearches(syncId: Int?) = delegate.trackSearches(syncId) override fun syncPreferences() = delegate.syncPreferences() override fun changedParts() = delegate.changedParts() override fun customButtons() = delegate.customButtons() override fun pageCache(chapterId: Long?) = delegate.pageCache(chapterId) override fun outbox() = delegate.outbox() // ── writes (in-memory + Room queue) ───────────────────────────────────── override fun updateSettings(settings: DbSettings) = tracked({ delegate.updateSettings(settings) }) { room.settingsDao().upsert(settings.toRow()) } override fun replaceAll( snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot?, ) = replaceAllSynchronously(snapshot, expectedSnapshot, null) override fun upsertManga(manga: DbManga): DbManga = batchLock.withLock { val previousCast = delegate.manga(manga.id)?.cast tracked({ delegate.upsertManga(manga) }) { saved -> room.mangaDao().upsert(saved.toRow()) if (previousCast != saved.cast) { room.mangaCreditDao().deleteForManga(saved.id) if (saved.cast.isNotEmpty()) room.mangaCreditDao().upsertAll(saved.toCreditRows()) } } } override fun removeManga(id: Long, recordChange: Boolean) = tracked({ delegate.removeManga(id, recordChange) }) { room.mangaDao().delete(id) } override fun upsertChapter(chapter: DbChapter): DbChapter = tracked({ delegate.upsertChapter(chapter) }) { saved -> room.chapterDao().upsert(saved.toRow()) } override fun removeChapter(id: Long, recordChange: Boolean) = tracked({ delegate.removeChapter(id, recordChange) }) { room.chapterDao().delete(id) room.pageCacheDao().delete(id) } override fun upsertCategory(category: DbCategory): DbCategory = tracked({ delegate.upsertCategory(category) }) { saved -> room.categoryDao().upsert(saved.toRow()) } override fun removeCategory(id: Long, recordChange: Boolean) = tracked({ delegate.removeCategory(id, recordChange) }) { room.categoryDao().delete(id) } override fun upsertSource(source: DbSource): DbSource { return mutate({ delegate.upsertSource(source) }) { saved -> room.sourceDao().upsert(saved.toRow()) } } override fun removeSource(id: Long) { mutate({ delegate.removeSource(id) }) { room.sourceDao().delete(id) } } override fun upsertHistory(history: DbHistory): DbHistory = tracked({ delegate.upsertHistory(history) }) { saved -> room.historyDao().upsert(saved.toRow()) } override fun removeHistory(id: Long, recordChange: Boolean) = tracked({ delegate.removeHistory(id, recordChange) }) { room.historyDao().delete(id) } override fun upsertUpdate(update: DbUpdate): DbUpdate = tracked({ delegate.upsertUpdate(update) }) { saved -> room.updateDao().upsert(saved.toRow()) } override fun removeUpdate(id: Long, recordChange: Boolean) = tracked({ delegate.removeUpdate(id, recordChange) }) { room.updateDao().delete(id) } override fun upsertDownload(download: DbDownload): DbDownload { return mutate({ delegate.upsertDownload(download) }) { saved -> room.downloadDao().upsert(saved.toRow()) } } override fun removeDownload(id: Long) { mutate({ delegate.removeDownload(id) }) { room.downloadDao().delete(id) } } override fun upsertTrack(track: DbTrack): DbTrack = tracked({ delegate.upsertTrack(track) }) { saved -> room.trackDao().upsert(saved.toRow()) } override fun removeTrack(id: Long, recordChange: Boolean) = tracked({ delegate.removeTrack(id, recordChange) }) { room.trackDao().delete(id) } override fun upsertTrackPreference(preference: DbTrackPreference): DbTrackPreference { return mutate({ delegate.upsertTrackPreference(preference) }) { saved -> room.trackPreferenceDao().upsert(saved.toRow()) } } override fun upsertTrackSearch(search: DbTrackSearch): DbTrackSearch { return mutate({ delegate.upsertTrackSearch(search) }) { saved -> room.trackSearchDao().upsert(saved.toRow()) } } override fun upsertSyncPreference(preference: DbSyncPreference): DbSyncPreference { return mutate({ delegate.upsertSyncPreference(preference) }) { saved -> room.syncPreferenceDao().upsert(saved.toRow()) } } override suspend fun upsertSyncPreferenceIf( syncId: Long, accepts: (DbSyncPreference?) -> Boolean, transform: (DbSyncPreference?) -> DbSyncPreference, ): Boolean { val accepted = batchLock.withLock { check(acceptingWrites) { "Room database is retiring or closed" } val current = delegate.syncPreferences().firstOrNull { it.syncId == syncId } if (!accepts(current)) return@withLock false val updated = delegate.upsertSyncPreference(transform(current).copy(syncId = syncId)) queueWrite { room.syncPreferenceDao().upsert(updated.toRow()) } true } if (accepted) withContext(NonCancellable) { awaitPersistence() } return accepted } override fun recordChange(change: DbChangedPart): DbChangedPart { return mutate({ delegate.recordChange(change) }) { saved -> room.changedPartDao().upsert(saved.toRow()) } } override fun clearChangedParts() { mutate({ delegate.clearChangedParts() }) { room.changedPartDao().clear() } } override fun upsertCustomButton(button: DbCustomButton): DbCustomButton { return mutate({ delegate.upsertCustomButton(button) }) { saved -> room.customButtonDao().upsert(saved.toRow()) } } override fun removeCustomButton(id: Long) { mutate({ delegate.removeCustomButton(id) }) { room.customButtonDao().delete(id) } } override fun upsertPageCache(cache: DbChapterPageUrls): DbChapterPageUrls = batchLock.withLock { check(acceptingWrites) { "Room database is retiring or closed" } val before = delegate.pageCache().mapNotNullTo(HashSet()) { it.chapterId } val saved = delegate.upsertPageCache(cache) val evicted = before - delegate.pageCache().mapNotNullTo(HashSet()) { it.chapterId } queueWrite { room.pageCacheDao().upsert(saved.toRow()) evicted.forEach { room.pageCacheDao().delete(it) } } saved } override fun removePageCache(chapterIds: Collection) { val ids = chapterIds.toList() if (ids.isEmpty()) return mutate({ delegate.removePageCache(ids) }) { ids.forEach { room.pageCacheDao().delete(it) } } } override fun clearPageCache() { mutate({ delegate.clearPageCache() }) { room.pageCacheDao().clear() } } // ── hub sync ──────────────────────────────────────────────────────────── override fun removeOutbox(ops: List) { mutate({ delegate.removeOutbox(ops) }) { ops.forEach { room.outboxDao().deleteIfUnchanged(it.kind, it.id, it.path, it.seq) } } } override suspend fun resyncHub(syncId: Long, epoch: Int): DbSyncPreference { val updated = batchLock.withLock { check(acceptingWrites) { "Room database is retiring or closed" } val current = delegate.syncPreferences().firstOrNull { it.syncId == syncId } ?: DbSyncPreference(syncId = syncId) val (resynced, dropBefore) = current.hubResync(epoch) val stale = dropBefore?.let { floor -> delegate.outbox().filter { it.epoch < floor } }.orEmpty() val updated = delegate.batch { delegate.removeOutbox(stale) delegate.upsertSyncPreference(resynced) } // Queued under the lock so no later write to the same rows can overtake it. queueWrite { room.syncPreferenceDao().upsert(updated.toRow()) stale.forEach { room.outboxDao().deleteIfUnchanged(it.kind, it.id, it.path, it.seq) } } updated } withContext(NonCancellable) { awaitPersistence() } return updated } override fun applyRemote(block: () -> T): T = batchLock.withLock { check(acceptingWrites) { "Room database is retiring or closed" } remoteApplyDepth++ try { delegate.applyRemote(block) } finally { remoteApplyDepth-- } } override fun batch(block: () -> T): T = batchLock.withLock { check(acceptingWrites) { "Room database is retiring or closed" } persistenceBatchDepth++ try { delegate.batch(block) } finally { persistenceBatchDepth-- if (persistenceBatchDepth == 0 && batchedWrites.isNotEmpty()) { val batched = batchedWrites.toList() batchedWrites.clear() // One queued action, so the whole batch always lands in the same transaction. enqueue { batched.forEach { it() } } } } } /** * Run a synced mutation on the delegate, then queue its Room row write together with * whatever outbox ops the mutation appended. */ private inline fun tracked(crossinline mutation: () -> T, crossinline persist: suspend (T) -> Unit): T = batchLock.withLock { check(acceptingWrites) { "Room database is retiring or closed" } val oldChangedIds = delegate.changedParts().mapTo(HashSet(), DbChangedPart::id) val (result, ops) = delegate.recordingOutbox { mutation() } val rows = ops.map { it.toRow() } val changedRows = delegate.changedParts().filter { it.id !in oldChangedIds }.map { it.toRow() } queueWrite { persist(result) if (rows.isNotEmpty()) room.outboxDao().upsertAll(rows) if (changedRows.isNotEmpty()) room.changedPartDao().upsertAll(changedRows) } result } private inline fun mutate(crossinline mutation: () -> T, crossinline persist: suspend (T) -> Unit): T = batchLock.withLock { check(acceptingWrites) { "Room database is retiring or closed" } val result = mutation() queueWrite { persist(result) } result } private fun queueWrite(action: suspend () -> Unit) { batchLock.withLock { if (persistenceBatchDepth > 0) batchedWrites += action else enqueue(action = action) } } /** [coalesce]d writes share the worker's next transaction; others bring their own. */ private fun enqueue(coalesce: Boolean = true, action: suspend () -> Unit) { check(writes.trySend(QueuedWrite(coalesce, action)).isSuccess) { "Room write queue is closed" } } /** Run [action] in its own transaction once everything queued before it is committed. */ private suspend fun enqueueAndAwait(action: suspend () -> Unit) { val completion = CompletableDeferred() enqueue(coalesce = false) { try { inTransaction(action) completion.complete(Unit) } catch (error: Throwable) { // Always release the blocked caller, but let cancellation keep propagating. completion.completeExceptionally(error) if (error is CancellationException) throw error } } withContext(NonCancellable) { completion.await() } } private suspend fun commit(pending: MutableList Unit>) { if (pending.isEmpty()) return val actions = pending.toList() pending.clear() retrying { inTransaction { actions.forEach { it() } } } } private suspend fun retrying(write: suspend () -> Unit) { var attempt = 0 while (true) { try { write() return } catch (error: Throwable) { if (error is CancellationException) throw error attempt++ AppLogger.error("[room] write failed (attempt $attempt; retrying): ${error.message.orEmpty()}") delay((50L shl attempt.coerceAtMost(6)).coerceAtMost(MAX_WRITE_RETRY_DELAY_MS)) } } } private suspend fun inTransaction(block: suspend () -> Unit) { room.useWriterConnection { connection -> connection.withTransaction(Transactor.SQLiteTransactionType.IMMEDIATE) { block() } } } private fun replaceAllSynchronously( snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot?, callerJob: Job?, removedSourceIds: Set = emptySet(), remoteApply: Boolean = false, ) = batchLock.withLock { check(acceptingWrites) { "Room database is retiring or closed" } check(persistenceBatchDepth == 0) { "Snapshot replacement cannot run inside a mutation batch" } check(remoteApplyDepth == 0) { "Snapshot replacement cannot run inside remote apply" } callerJob?.ensureActive() if (expectedSnapshot != null && delegate.snapshot() != expectedSnapshot) { throw SnapshotReplacementConflictException() } val expectedSourceIds = delegate.sources().mapTo(HashSet(), DbSource::id) if (removedSourceIds.isNotEmpty() && (!expectedSourceIds.containsAll(removedSourceIds) || snapshot.sources.any { it.id in removedSourceIds }) ) { throw SnapshotReplacementConflictException() } val target = if (remoteApply) snapshot else snapshot.withMangayomiLocalSyncTimestamps(delegate.snapshot()).withMangayomiDeletes(delegate.snapshot()) // Blocks by contract: the snapshot is published only after Room committed it. The // suspending replaceAllAtomically runs this on roomReplacementDispatcher instead. runBlocking { enqueueAndAwait { if (removedSourceIds.isNotEmpty()) { removeRecipeInstallations(removedSourceIds, expectedSourceIds) } writeAllTables(target, clearFirst = true) } } delegate.applyRemote { delegate.replaceAll(target) } } private suspend fun removeRecipeInstallations(removedSourceIds: Set, expectedSourceIds: Set) { val actualSourceIds = room.sourceDao().all().mapTo(HashSet()) { it.id } if (actualSourceIds != expectedSourceIds) throw SnapshotReplacementConflictException() val installationDao = room.recipeInstallationDao() val affected = installationDao.allInstalled().filter { row -> if (row.catalogId.isBlank() || row.stableId.isBlank() || row.catalogRevision < 0) { throw IllegalStateException("Corrupt recipe installation") } val expectedId = recipeSourceId(row.catalogId, row.stableId) if (row.sourceId != null && row.sourceId != expectedId) { throw IllegalStateException("Corrupt recipe source association") } (row.sourceId ?: expectedId) in removedSourceIds } val byCatalog = affected.groupBy { it.catalogId } for ((catalogId, rows) in byCatalog) { val checkpoint = installationDao.checkpoint(catalogId) ?: throw IllegalStateException("Corrupt recipe catalog checkpoint") if (checkpoint.catalogId != catalogId || checkpoint.generation < 0) { throw IllegalStateException("Corrupt recipe catalog checkpoint") } if (checkpoint.generation == Long.MAX_VALUE) { throw IllegalStateException("Recipe catalog generation overflow") } rows.forEach { installationDao.deleteInstalled(it.catalogId, it.stableId) } installationDao.upsertCheckpoint(checkpoint.copy(generation = checkpoint.generation + 1)) } } private suspend fun readAllFromRoom(): YokanDatabaseSnapshot? = coroutineScope { // Fan-out every table read on the dedicated Room dispatcher. SQLite // serializes statements internally, and this view also orders the // worker's writes, hydration, and startup import. val mangasJob = async { val credits = room.mangaCreditDao().all().groupBy({ it.mangaId }, { it.toCredit() }) room.mangaDao().all().map { it.toDb().copy(cast = credits[it.id].orEmpty()) } } val chaptersJob = async { room.chapterDao().all().map(ChapterRow::toDb) } val categoriesJob = async { room.categoryDao().all().map(CategoryRow::toDb) } val sourcesJob = async { room.sourceDao().all().map(SourceRow::toDb) } val historiesJob = async { room.historyDao().all().map(HistoryRow::toDb) } val updatesJob = async { room.updateDao().all().map(UpdateRow::toDb) } val downloadsJob = async { room.downloadDao().all().map(DownloadRow::toDb) } val tracksJob = async { room.trackDao().all().map(TrackRow::toDb) } val trackPrefsJob = async { room.trackPreferenceDao().all().map(TrackPreferenceRow::toDb) } val trackSearchesJob = async { room.trackSearchDao().all().map(TrackSearchRow::toDb) } val syncPrefsJob = async { room.syncPreferenceDao().all().map(SyncPreferenceRow::toDb) } val changedPartsJob = async { room.changedPartDao().all().map(ChangedPartRow::toDb) } val customButtonsJob = async { room.customButtonDao().all().map(CustomButtonRow::toDb) } val pageCacheJob = async { room.pageCacheDao().all().map(PageCacheRow::toDb) } val outboxJob = async { room.outboxDao().all().map(OutboxRow::toDb) } val settingsJob = async { room.settingsDao().get() } // awaitAll on each list one at a time to keep the structured-concurrency // surface tidy and let the JIT cache the Db* mappers. val mangas = mangasJob.await() val chapters = chaptersJob.await() val settingsRow = settingsJob.await() // Treat an empty Room (no rows AND no settings blob) as "first // launch" so the caller can seed from the legacy JSON snapshot. if (settingsRow == null && mangas.isEmpty() && chapters.isEmpty()) { awaitAll( categoriesJob, sourcesJob, historiesJob, updatesJob, downloadsJob, tracksJob, trackPrefsJob, trackSearchesJob, syncPrefsJob, changedPartsJob, customButtonsJob, pageCacheJob, outboxJob, ) return@coroutineScope null } YokanDatabaseSnapshot( settings = settingsRow?.toDb() ?: DbSettings(), mangas = mangas, chapters = chapters, categories = categoriesJob.await(), sources = sourcesJob.await(), histories = historiesJob.await(), updates = updatesJob.await(), downloads = downloadsJob.await(), tracks = tracksJob.await(), trackPreferences = trackPrefsJob.await(), trackSearches = trackSearchesJob.await(), syncPreferences = syncPrefsJob.await(), changedParts = changedPartsJob.await(), customButtons = customButtonsJob.await(), pageCache = pageCacheJob.await(), outbox = outboxJob.await(), ) } private suspend fun writeAllTables(snapshot: YokanDatabaseSnapshot, clearFirst: Boolean) { room.settingsDao().upsert(snapshot.settings.toRow()) if (clearFirst) { room.mangaCreditDao().clear() room.mangaDao().clear() room.chapterDao().clear() room.categoryDao().clear() room.sourceDao().clear() room.historyDao().clear() room.updateDao().clear() room.downloadDao().clear() room.trackDao().clear() room.trackPreferenceDao().clear() room.trackSearchDao().clear() room.syncPreferenceDao().clear() room.changedPartDao().clear() room.customButtonDao().clear() room.pageCacheDao().clear() room.outboxDao().clear() } room.mangaDao().upsertAll(snapshot.mangas.map { it.toRow() }) room.mangaCreditDao().upsertAll(snapshot.mangas.flatMap { it.toCreditRows() }) room.chapterDao().upsertAll(snapshot.chapters.map { it.toRow() }) room.categoryDao().upsertAll(snapshot.categories.map { it.toRow() }) room.sourceDao().upsertAll(snapshot.sources.map { it.toRow() }) room.historyDao().upsertAll(snapshot.histories.map { it.toRow() }) room.updateDao().upsertAll(snapshot.updates.map { it.toRow() }) room.downloadDao().upsertAll(snapshot.downloads.map { it.toRow() }) room.trackDao().upsertAll(snapshot.tracks.map { it.toRow() }) room.trackPreferenceDao().upsertAll(snapshot.trackPreferences.map { it.toRow() }) room.trackSearchDao().upsertAll(snapshot.trackSearches.map { it.toRow() }) room.syncPreferenceDao().upsertAll(snapshot.syncPreferences.map { it.toRow() }) room.changedPartDao().upsertAll(snapshot.changedParts.map { it.toRow() }) room.customButtonDao().upsertAll(snapshot.customButtons.map { it.toRow() }) room.pageCacheDao().upsertAll(snapshot.pageCache.map { it.toRow() }) room.outboxDao().upsertAll(snapshot.outbox.map { it.toRow() }) } private suspend fun importSnapshot(snapshot: YokanDatabaseSnapshot) { // Only runs against a cold (empty) Room, so no clears needed. room.useWriterConnection { connection -> connection.withTransaction(Transactor.SQLiteTransactionType.IMMEDIATE) { writeAllTables(snapshot, clearFirst = false) } } AppLogger.info( "[room] hydrated initial snapshot: " + "mangas=${snapshot.mangas.size} chapters=${snapshot.chapters.size} " + "histories=${snapshot.histories.size}", ) } /** A queued Room write; [coalesce]d writes run inside one shared transaction. */ private class QueuedWrite(val coalesce: Boolean, val action: suspend () -> Unit) private companion object { const val MAX_WRITE_RETRY_DELAY_MS = 5_000L } } private fun YokanDatabaseSnapshot.withMangayomiDeletes(before: YokanDatabaseSnapshot): YokanDatabaseSnapshot { val additions = mangayomiDeleteParts(before, this, changedParts, nowMillis()) return if (additions.isEmpty()) this else copy(changedParts = changedParts + additions) }