InMemoryYokanDatabase.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/InMemoryYokanDatabase.kt
1package eu.friedcutlet.yokan.database23import eu.friedcutlet.yokan.database.sync.SyncClock4import eu.friedcutlet.yokan.database.sync.SyncIds5import eu.friedcutlet.yokan.database.sync.SyncPaths6import eu.friedcutlet.yokan.database.sync.hubResync7import eu.friedcutlet.yokan.database.sync.mangayomiDeleteParts8import eu.friedcutlet.yokan.util.PlatformLock9import eu.friedcutlet.yokan.util.nowMillis10import kotlinx.coroutines.flow.MutableStateFlow11import kotlinx.coroutines.flow.StateFlow12import kotlinx.serialization.KSerializer13import kotlinx.serialization.json.JsonObject14import kotlinx.serialization.json.JsonPrimitive1516/** Chapter page lists kept by [InMemoryYokanDatabase.upsertPageCache]; older ones are refetched (page URLs expire anyway). */17internal const val MAX_PAGE_CACHE = 1001819class InMemoryYokanDatabase(20 initial: YokanDatabaseSnapshot = seedDatabaseSnapshot(),21) : YokanDatabase {22 private val lock = PlatformLock()23 private var settings = initial.settings24 private val mangas = Table(initial.mangas, DbManga::id)25 private val chapters = Table(initial.chapters, DbChapter::id)26 private val categories = Table(initial.categories, DbCategory::id)27 private val sources = Table(initial.sources, DbSource::id)28 private val histories = Table(initial.histories, DbHistory::id)29 private val updates = Table(initial.updates, DbUpdate::id)30 private val downloads = Table(initial.downloads, DbDownload::id)31 private val tracks = Table(initial.tracks, DbTrack::id)32 private val trackPreferences = initial.trackPreferences.toMutableList()33 private val trackSearches = initial.trackSearches.toMutableList()34 private val syncPreferences = initial.syncPreferences.toMutableList()35 private val changedParts = Table(initial.changedParts, DbChangedPart::id)36 private val customButtons = Table(initial.customButtons, DbCustomButton::id)37 private val pageCache = initial.pageCache.toMutableList()3839 /** Keyed by (kind, id, path) so a rewrite replaces its op in O(1); iteration order is seq order. */40 private val outbox = LinkedHashMap<OutboxKey, DbOutboxOp>()41 private var outboxSeq = initial.outbox.maxOfOrNull { it.seq } ?: 0L42 private var suppressOutbox = 043 private var batchDepth = 044 private var newOutboxOps: MutableList<DbOutboxOp>? = null45 private var lastDocValue: Any? = null46 private var lastDoc: JsonObject? = null47 private val dirtySnapshotParts = mutableSetOf<SnapshotPart>()4849 init {50 resetOutbox(initial.outbox)51 // Epoch-0 ops from before recording required a logged-in hub: no hub ever accepts them52 // (the first sync seeds full state instead), so they were only growing the database.53 if (activeHubEpoch() == null) outbox.values.removeAll { it.epoch == 0 }54 }5556 private val snapshotState = MutableStateFlow(createSnapshot())5758 override fun snapshot(): YokanDatabaseSnapshot = lock.withLock(::current)5960 override fun snapshots(): StateFlow<YokanDatabaseSnapshot> = snapshotState6162 override fun supportsAtomicSnapshotPersistence(): Boolean = true6364 override suspend fun replaceAllAtomically(65 snapshot: YokanDatabaseSnapshot,66 expectedSnapshot: YokanDatabaseSnapshot?,67 removedSourceIds: Set<Long>,68 ) {69 replaceAll(snapshot, expectedSnapshot)70 }7172 override suspend fun replaceAllRemoteAtomically(snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot?) {73 applyRemote { replaceAll(snapshot, expectedSnapshot) }74 }7576 override fun replaceAll(77 snapshot: YokanDatabaseSnapshot,78 expectedSnapshot: YokanDatabaseSnapshot?,79 ) = lock.withLock {80 if (expectedSnapshot != null && current() != expectedSnapshot) {81 throw SnapshotReplacementConflictException()82 }83 val before = current()84 val replacement = if (suppressOutbox > 0) snapshot else snapshot.withMangayomiLocalSyncTimestamps(before)85 fun <T> MutableList<T>.reset(items: List<T>) {86 clear()87 addAll(items)88 }89 settings = replacement.settings90 mangas.reset(replacement.mangas)91 chapters.reset(replacement.chapters)92 categories.reset(replacement.categories)93 sources.reset(replacement.sources)94 histories.reset(replacement.histories)95 updates.reset(replacement.updates)96 downloads.reset(replacement.downloads)97 tracks.reset(replacement.tracks)98 trackPreferences.reset(replacement.trackPreferences)99 trackSearches.reset(replacement.trackSearches)100 syncPreferences.reset(replacement.syncPreferences)101 changedParts.reset(replacement.changedParts)102 customButtons.reset(replacement.customButtons)103 pageCache.reset(replacement.pageCache)104 resetOutbox(replacement.outbox)105 outboxSeq = replacement.outbox.maxOfOrNull { it.seq } ?: 0L106 if (suppressOutbox == 0) {107 mangayomiDeleteParts(before, replacement, changedParts.rows.toList(), nowMillis()).forEach(::recordChange)108 }109 dirtySnapshotParts.clear()110 snapshotState.value = createSnapshot()111 }112113 /** The published snapshot is current whenever nothing is pending, so reads skip the full copy. */114 private fun current(): YokanDatabaseSnapshot =115 if (dirtySnapshotParts.isEmpty()) snapshotState.value else createSnapshot()116117 private fun createSnapshot(): YokanDatabaseSnapshot = YokanDatabaseSnapshot(118 settings = settings,119 mangas = mangas.rows.toList(),120 chapters = chapters.rows.toList(),121 categories = categories.rows.toList(),122 sources = sources.rows.toList(),123 histories = histories.rows.toList(),124 updates = updates.rows.toList(),125 downloads = downloads.rows.toList(),126 tracks = tracks.rows.toList(),127 trackPreferences = trackPreferences.toList(),128 trackSearches = trackSearches.toList(),129 syncPreferences = syncPreferences.toList(),130 changedParts = changedParts.rows.toList(),131 customButtons = customButtons.rows.toList(),132 pageCache = pageCache.toList(),133 outbox = outbox.values.toList(),134 )135136 override fun settings(): DbSettings = lock.withLock { settings }137138 override fun updateSettings(settings: DbSettings) = lock.withLock {139 val before = this.settings140 this.settings = settings141 if (before != settings) {142 recordDoc(SyncPaths.KIND_SETTINGS, SyncPaths.SETTINGS_ID, before, settings, DbSettings.serializer())143 }144 emitSnapshot(SnapshotPart.Settings)145 }146147 override fun mangas(itemType: DbItemType?): List<DbManga> = lock.withLock {148 mangas.rows.filter { itemType == null || it.itemType == itemType }149 }150151 override fun manga(id: Long): DbManga? = lock.withLock { mangas[id] }152153 override fun upsertManga(manga: DbManga): DbManga = lock.withLock {154 val identified = if (manga.id == 0L) assignId(manga) else manga155 val old = mangas[identified.id]156 val value = localTimestamp(identified, old, SyncPaths.KIND_MANGA, DbManga.serializer(), DbManga::updatedAt) { row, at -> row.copy(updatedAt = at) }157 upsert(mangas, value, SyncPaths.KIND_MANGA, DbManga.serializer()).also { emitSnapshot(SnapshotPart.Mangas) }158 }159160 override fun removeManga(id: Long, recordChange: Boolean) = lock.withLock {161 if (mangas.remove(id) && recordChange) { recordDelete(SyncPaths.KIND_MANGA, id); recordMangayomiDelete(SyncPaths.KIND_MANGA, id, DbActionType.RemoveItem) }162 emitSnapshot(SnapshotPart.Mangas)163 }164165 override fun chapters(mangaId: Long?): List<DbChapter> = lock.withLock {166 chapters.rows.filter { mangaId == null || it.mangaId == mangaId }167 }168169 override fun chapter(id: Long): DbChapter? = lock.withLock { chapters[id] }170171 override fun upsertChapter(chapter: DbChapter): DbChapter = lock.withLock {172 val identified = if (chapter.id == 0L) assignId(chapter) else chapter173 val old = chapters[identified.id]174 val value = localTimestamp(identified, old, SyncPaths.KIND_CHAPTER, DbChapter.serializer(), DbChapter::updatedAt) { row, at -> row.copy(updatedAt = at) }175 upsert(chapters, value, SyncPaths.KIND_CHAPTER, DbChapter.serializer()).also { emitSnapshot(SnapshotPart.Chapters) }176 }177178 override fun removeChapter(id: Long, recordChange: Boolean) = lock.withLock {179 if (chapters.remove(id) && recordChange) { recordDelete(SyncPaths.KIND_CHAPTER, id); recordMangayomiDelete(SyncPaths.KIND_CHAPTER, id, DbActionType.RemoveChapter) }180 if (pageCache.removeAll { it.chapterId == id }) dirtySnapshotParts += SnapshotPart.PageCache181 emitSnapshot(SnapshotPart.Chapters)182 }183184 override fun categories(itemType: DbItemType?): List<DbCategory> = lock.withLock {185 categories.rows.filter { itemType == null || it.forItemType == itemType }.sortedBy { it.position ?: 0 }186 }187188 override fun upsertCategory(category: DbCategory): DbCategory = lock.withLock {189 val identified = if (category.id == 0L) assignId(category) else category190 val old = categories[identified.id]191 val value = localTimestamp(identified, old, SyncPaths.KIND_CATEGORY, DbCategory.serializer(), DbCategory::updatedAt) { row, at -> row.copy(updatedAt = at) }192 upsert(categories, value, SyncPaths.KIND_CATEGORY, DbCategory.serializer()).also { emitSnapshot(SnapshotPart.Categories) }193 }194195 override fun removeCategory(id: Long, recordChange: Boolean) = lock.withLock {196 if (categories.remove(id) && recordChange) { recordDelete(SyncPaths.KIND_CATEGORY, id); recordMangayomiDelete(SyncPaths.KIND_CATEGORY, id, DbActionType.RemoveCategory) }197 emitSnapshot(SnapshotPart.Categories)198 }199200 override fun sources(itemType: DbItemType?): List<DbSource> = lock.withLock {201 // Strict item-type match. Local sources used to leak into every tab202 // via `|| it.isLocal`, which mixed Anime archives into the Manga203 // browse tab. If a user has local archives for multiple item types,204 // they need separate local sources per type.205 sources.rows.filter { itemType == null || it.itemType == itemType }206 }207208 override fun source(id: Long): DbSource? = lock.withLock { sources[id] }209210 override fun upsertSource(source: DbSource): DbSource = lock.withLock {211 upsert(sources, source).also { emitSnapshot(SnapshotPart.Sources) }212 }213214 override fun removeSource(id: Long) = lock.withLock {215 batch {216 sources.remove(id)217 recordChange(DbChangedPart(actionType = DbActionType.RemoveExtension, isarId = id, data = "", clientDate = nowMillis()))218 emitSnapshot(SnapshotPart.Sources)219 }220 }221222 override fun histories(): List<DbHistory> = lock.withLock { histories.rows.toList() }223224 override fun upsertHistory(history: DbHistory): DbHistory = lock.withLock {225 val identified = if (history.id == 0L) assignId(history) else history226 val old = histories[identified.id]227 val value = localTimestamp(identified, old, SyncPaths.KIND_HISTORY, DbHistory.serializer(), DbHistory::updatedAt) { row, at -> row.copy(updatedAt = at) }228 upsert(histories, value, SyncPaths.KIND_HISTORY, DbHistory.serializer()).also { emitSnapshot(SnapshotPart.Histories) }229 }230231 override fun removeHistory(id: Long, recordChange: Boolean) = lock.withLock {232 if (histories.remove(id) && recordChange) { recordDelete(SyncPaths.KIND_HISTORY, id); recordMangayomiDelete(SyncPaths.KIND_HISTORY, id, DbActionType.RemoveHistory) }233 emitSnapshot(SnapshotPart.Histories)234 }235236 override fun updates(): List<DbUpdate> = lock.withLock { updates.rows.toList() }237238 override fun upsertUpdate(update: DbUpdate): DbUpdate = lock.withLock {239 val identified = if (update.id == 0L) assignId(update) else update240 val old = updates[identified.id]241 val value = localTimestamp(identified, old, SyncPaths.KIND_UPDATE, DbUpdate.serializer(), DbUpdate::updatedAt) { row, at -> row.copy(updatedAt = at) }242 upsert(updates, value, SyncPaths.KIND_UPDATE, DbUpdate.serializer()).also { emitSnapshot(SnapshotPart.Updates) }243 }244245 override fun removeUpdate(id: Long, recordChange: Boolean) = lock.withLock {246 if (updates.remove(id) && recordChange) { recordDelete(SyncPaths.KIND_UPDATE, id); recordMangayomiDelete(SyncPaths.KIND_UPDATE, id, DbActionType.RemoveUpdate) }247 emitSnapshot(SnapshotPart.Updates)248 }249250 override fun downloads(): List<DbDownload> = lock.withLock { downloads.rows.toList() }251252 override fun download(id: Long): DbDownload? = lock.withLock { downloads[id] }253254 override fun upsertDownload(download: DbDownload): DbDownload = lock.withLock {255 upsert(downloads, download).also { emitSnapshot(SnapshotPart.Downloads) }256 }257258 override fun removeDownload(id: Long) = lock.withLock {259 downloads.remove(id)260 emitSnapshot(SnapshotPart.Downloads)261 }262263 override fun tracks(mangaId: Long?): List<DbTrack> = lock.withLock {264 tracks.rows.filter { mangaId == null || it.mangaId == mangaId }265 }266267 override fun upsertTrack(track: DbTrack): DbTrack = lock.withLock {268 val identified = if (track.id == 0L) assignId(track) else track269 val old = tracks[identified.id]270 val value = localTimestamp(identified, old, SyncPaths.KIND_TRACK, DbTrack.serializer(), DbTrack::updatedAt) { row, at -> row.copy(updatedAt = at) }271 upsert(tracks, value, SyncPaths.KIND_TRACK, DbTrack.serializer()).also { emitSnapshot(SnapshotPart.Tracks) }272 }273274 override fun removeTrack(id: Long, recordChange: Boolean) = lock.withLock {275 if (tracks.remove(id) && recordChange) { recordDelete(SyncPaths.KIND_TRACK, id); recordMangayomiDelete(SyncPaths.KIND_TRACK, id, DbActionType.RemoveTrack) }276 emitSnapshot(SnapshotPart.Tracks)277 }278279 override fun trackPreferences(): List<DbTrackPreference> = lock.withLock { trackPreferences.toList() }280281 override fun upsertTrackPreference(preference: DbTrackPreference): DbTrackPreference = lock.withLock {282 upsertNullableKey(trackPreferences, preference, DbTrackPreference::syncId).also { emitSnapshot(SnapshotPart.TrackPreferences) }283 }284285 override fun trackSearches(syncId: Int?): List<DbTrackSearch> = lock.withLock {286 trackSearches.filter { syncId == null || it.syncId == syncId }287 }288289 override fun upsertTrackSearch(search: DbTrackSearch): DbTrackSearch = lock.withLock {290 upsertNullableKey(trackSearches, search, DbTrackSearch::id).also { emitSnapshot(SnapshotPart.TrackSearches) }291 }292293 override fun syncPreferences(): List<DbSyncPreference> = lock.withLock { syncPreferences.toList() }294295 override fun upsertSyncPreference(preference: DbSyncPreference): DbSyncPreference = lock.withLock {296 upsertNullableKey(syncPreferences, preference, DbSyncPreference::syncId).also { emitSnapshot(SnapshotPart.SyncPreferences) }297 }298299 override suspend fun upsertSyncPreferenceIf(300 syncId: Long,301 accepts: (DbSyncPreference?) -> Boolean,302 transform: (DbSyncPreference?) -> DbSyncPreference,303 ): Boolean = lock.withLock {304 val current = syncPreferences.firstOrNull { it.syncId == syncId }305 if (!accepts(current)) return@withLock false306 val updated = transform(current).copy(syncId = syncId)307 upsertNullableKey(syncPreferences, updated, DbSyncPreference::syncId)308 emitSnapshot(SnapshotPart.SyncPreferences)309 true310 }311312 override fun changedParts(): List<DbChangedPart> = lock.withLock { changedParts.rows.toList() }313314 override fun recordChange(change: DbChangedPart): DbChangedPart = lock.withLock {315 val used = changedParts.rows.mapTo(HashSet(), DbChangedPart::id)316 var id = change.id.takeIf { it > 0 && it !in used } ?: SyncIds.random()317 while (id in used) id = SyncIds.random()318 upsert(changedParts, change.copy(id = id)).also {319 emitSnapshot(SnapshotPart.ChangedParts)320 }321 }322323 override fun clearChangedParts() = lock.withLock {324 changedParts.reset(emptyList())325 emitSnapshot(SnapshotPart.ChangedParts)326 }327328 override fun customButtons(): List<DbCustomButton> = lock.withLock { customButtons.rows.sortedBy { it.position } }329330 override fun upsertCustomButton(button: DbCustomButton): DbCustomButton = lock.withLock {331 upsert(customButtons, button).also { emitSnapshot(SnapshotPart.CustomButtons) }332 }333334 override fun removeCustomButton(id: Long) = lock.withLock {335 customButtons.remove(id)336 emitSnapshot(SnapshotPart.CustomButtons)337 }338339 override fun pageCache(chapterId: Long?): List<DbChapterPageUrls> = lock.withLock {340 pageCache.filter { chapterId == null || it.chapterId == chapterId }341 }342343 override fun upsertPageCache(cache: DbChapterPageUrls): DbChapterPageUrls = lock.withLock {344 cache.chapterId?.let { id -> pageCache.removeAll { it.chapterId == id } }345 pageCache += cache346 // ponytail: evicts by write order only; track read recency if the offline reader needs older lists.347 if (pageCache.size > MAX_PAGE_CACHE) pageCache.subList(0, pageCache.size - MAX_PAGE_CACHE).clear()348 emitSnapshot(SnapshotPart.PageCache)349 cache350 }351352 override fun removePageCache(chapterIds: Collection<Long>) {353 lock.withLock {354 if (pageCache.removeAll { it.chapterId in chapterIds }) emitSnapshot(SnapshotPart.PageCache)355 }356 }357358 override fun clearPageCache() = lock.withLock {359 pageCache.clear()360 emitSnapshot(SnapshotPart.PageCache)361 }362363 // ── hub sync ────────────────────────────────────────────────────────────364365 override fun outbox(): List<DbOutboxOp> = lock.withLock { outbox.values.toList() }366367 /** Runs [block] and also returns the outbox ops it appended, so the Room layer persists exactly those. */368 internal fun <T> recordingOutbox(block: () -> T): Pair<T, List<DbOutboxOp>> = lock.withLock {369 val outer = newOutboxOps370 val ops = ArrayList<DbOutboxOp>()371 newOutboxOps = ops372 try {373 block() to ops374 } finally {375 newOutboxOps = outer376 outer?.addAll(ops)377 }378 }379380 override fun removeOutbox(ops: List<DbOutboxOp>) = lock.withLock {381 if (ops.isEmpty()) return@withLock382 for (op in ops) {383 val key = op.key()384 if (outbox[key]?.seq == op.seq) outbox.remove(key)385 }386 emitSnapshot(SnapshotPart.Outbox)387 }388389 override suspend fun resyncHub(syncId: Long, epoch: Int): DbSyncPreference = lock.withLock {390 val current = syncPreferences.firstOrNull { it.syncId == syncId }391 ?: DbSyncPreference(syncId = syncId)392 val (updated, dropBefore) = current.hubResync(epoch)393 upsertNullableKey(syncPreferences, updated, DbSyncPreference::syncId)394 if (dropBefore != null) outbox.values.removeAll { it.epoch < dropBefore }395 dirtySnapshotParts += SnapshotPart.SyncPreferences396 dirtySnapshotParts += SnapshotPart.Outbox397 publishDirtySnapshot()398 updated399 }400401 override fun <T> applyRemote(block: () -> T): T = lock.withLock {402 suppressOutbox++403 try {404 block()405 } finally {406 suppressOutbox--407 }408 }409410 override fun <T> batch(block: () -> T): T = lock.withLock {411 batchDepth++412 try {413 block()414 } finally {415 batchDepth--416 if (batchDepth == 0) publishDirtySnapshot()417 }418 }419420 /**421 * Record the path-level difference between two versions of a row. Nothing is recorded while422 * no hub is logged in: the first sync seeds the hub with full local state, not the outbox.423 */424 private fun <T> recordDoc(kind: Int, id: Long, before: T?, after: T, serializer: KSerializer<T>) {425 if (suppressOutbox > 0) return426 val epoch = activeHubEpoch() ?: return427 val beforeDoc = before?.let { docOf(kind, serializer, it) }428 record(kind, id, SyncPaths.diff(kind, beforeDoc, docOf(kind, serializer, after)), epoch)429 }430431 private fun recordDelete(kind: Int, id: Long) {432 if (suppressOutbox > 0) return433 val epoch = activeHubEpoch() ?: return434 record(kind, id, listOf(SyncPaths.PathChange(SyncPaths.DELETED, JsonPrimitive(true))), epoch)435 }436437 private fun record(kind: Int, id: Long, changes: List<SyncPaths.PathChange>, epoch: Int) {438 for (change in changes) {439 val op = DbOutboxOp(440 kind = kind,441 id = id,442 path = change.path,443 value = change.value?.toString(),444 hlc = SyncClock.tick(),445 seq = ++outboxSeq,446 epoch = epoch,447 )448 putOutbox(op)449 newOutboxOps?.add(op)450 }451 if (changes.isNotEmpty()) dirtySnapshotParts += SnapshotPart.Outbox452 }453454 /** Wire doc of [value]. The last row's doc is kept, so rewriting a row (or settings) encodes it once. */455 private fun <T> docOf(kind: Int, serializer: KSerializer<T>, value: T): JsonObject {456 val cached = lastDoc457 if (cached != null && lastDocValue === value) return cached458 return SyncPaths.doc(kind, serializer, value).also {459 lastDocValue = value460 lastDoc = it461 }462 }463464 private fun putOutbox(op: DbOutboxOp) {465 val key = op.key()466 outbox.remove(key)467 outbox[key] = op468 }469470 private fun resetOutbox(ops: List<DbOutboxOp>) {471 outbox.clear()472 ops.sortedBy { it.seq }.forEach(::putOutbox)473 }474475 private fun activeHubEpoch(): Int? = SyncPaths.activeHubEpoch(syncPreferences)476477 private fun <T> localTimestamp(478 incoming: T,479 previous: T?,480 kind: Int,481 serializer: KSerializer<T>,482 timestamp: (T) -> Long,483 copyTimestamp: (T, Long) -> T,484 ): T {485 // Only Mangayomi's whole-row LWW needs this; Hub merges per path and must not see updatedAt churn.486 if (suppressOutbox > 0 || syncPreferences.none { it.serverProvider == SyncServerProvider.Mangayomi }) return incoming487 return copyTimestamp(incoming, SyncPaths.localUpdatedAt(kind, serializer, previous, incoming, timestamp))488 }489490 private fun recordMangayomiDelete(kind: Int, id: Long, action: DbActionType) {491 if (suppressOutbox > 0) return492 mangayomiDeleteParts(kind, id, action, syncPreferences.toList(), changedParts.rows.toList(), nowMillis()).forEach(::recordChange)493 }494495 private fun emitSnapshot(part: SnapshotPart) {496 dirtySnapshotParts += part497 if (batchDepth > 0) {498 return499 }500 publishDirtySnapshot()501 }502503 private fun publishDirtySnapshot() {504 if (dirtySnapshotParts.isEmpty()) return505 var next = snapshotState.value506 dirtySnapshotParts.forEach { part ->507 next = when (part) {508 SnapshotPart.Settings -> next.copy(settings = settings)509 SnapshotPart.Mangas -> next.copy(mangas = mangas.rows.toList())510 SnapshotPart.Chapters -> next.copy(chapters = chapters.rows.toList())511 SnapshotPart.Categories -> next.copy(categories = categories.rows.toList())512 SnapshotPart.Sources -> next.copy(sources = sources.rows.toList())513 SnapshotPart.Histories -> next.copy(histories = histories.rows.toList())514 SnapshotPart.Updates -> next.copy(updates = updates.rows.toList())515 SnapshotPart.Downloads -> next.copy(downloads = downloads.rows.toList())516 SnapshotPart.Tracks -> next.copy(tracks = tracks.rows.toList())517 SnapshotPart.TrackPreferences -> next.copy(trackPreferences = trackPreferences.toList())518 SnapshotPart.TrackSearches -> next.copy(trackSearches = trackSearches.toList())519 SnapshotPart.SyncPreferences -> next.copy(syncPreferences = syncPreferences.toList())520 SnapshotPart.ChangedParts -> next.copy(changedParts = changedParts.rows.toList())521 SnapshotPart.CustomButtons -> next.copy(customButtons = customButtons.rows.toList())522 SnapshotPart.PageCache -> next.copy(pageCache = pageCache.toList())523 SnapshotPart.Outbox -> next.copy(outbox = outbox.values.toList())524 }525 }526 dirtySnapshotParts.clear()527 snapshotState.value = next528 }529530 private enum class SnapshotPart {531 Settings,532 Mangas,533 Chapters,534 Categories,535 Sources,536 Histories,537 Updates,538 Downloads,539 Tracks,540 TrackPreferences,541 TrackSearches,542 SyncPreferences,543 ChangedParts,544 CustomButtons,545 PageCache,546 Outbox,547 }548549 private fun <T> upsert(550 table: Table<T>,551 item: T,552 kind: Int = 0,553 serializer: KSerializer<T>? = null,554 ): T {555 val normalized = if (table.key(item) == 0L) assignId(item) else item556 val id = table.key(normalized)557 val index = table.indexOf(id)558 val previous = if (index >= 0) table.rows[index] else null559 if (index >= 0) {560 table.rows[index] = normalized561 } else {562 table.add(normalized)563 }564 if (serializer != null && previous != normalized) recordDoc(kind, id, previous, normalized, serializer)565 return normalized566 }567568 private fun <T, K : Any> upsertNullableKey(items: MutableList<T>, item: T, key: (T) -> K?): T {569 val itemKey = key(item)570 val index = if (itemKey == null) -1 else items.indexOfFirst { key(it) == itemKey }571 if (index >= 0) {572 items[index] = item573 } else {574 items += item575 }576 return item577 }578579 /**580 * Synced entities get stable ids derived from their natural key ([SyncIds]) so devices agree581 * on identity without coordination; local-only tables keep a plain counter.582 */583 @Suppress("UNCHECKED_CAST")584 private fun <T> assignId(item: T): T = when (item) {585 is DbManga -> item.copy(id = SyncIds.forManga(item) ?: SyncIds.random())586 is DbChapter -> item.copy(id = SyncIds.forChapter(item) ?: SyncIds.random())587 is DbCategory -> item.copy(id = SyncIds.random())588 is DbHistory -> item.copy(id = SyncIds.forHistory(item) ?: SyncIds.random())589 is DbUpdate -> item.copy(id = SyncIds.forUpdate(item) ?: SyncIds.random())590 is DbTrack -> item.copy(id = SyncIds.forTrack(item) ?: SyncIds.random())591 is DbSource -> item.copy(id = nextId(sources.rows, DbSource::id))592 is DbDownload -> item.copy(id = nextId(downloads.rows, DbDownload::id))593 is DbChangedPart -> item.copy(id = nextId(changedParts.rows, DbChangedPart::id))594 is DbCustomButton -> item.copy(id = nextId(customButtons.rows, DbCustomButton::id))595 else -> item596 } as T597598 private fun <T> nextId(items: List<T>, key: (T) -> Long): Long =599 (items.maxOfOrNull(key) ?: 0L) + 1L600}601602/** Rows in insertion order plus a lazily rebuilt id → first-row index, so point lookups and upserts are O(1). */603private class Table<T>(initial: List<T>, val key: (T) -> Long) {604 val rows = ArrayList(initial)605 private var index: HashMap<Long, Int>? = null606607 fun indexOf(id: Long): Int {608 val map = index ?: HashMap<Long, Int>(rows.size).also { built ->609 rows.forEachIndexed { position, row -> built.getOrPut(key(row)) { position } }610 index = built611 }612 return map[id] ?: -1613 }614615 operator fun get(id: Long): T? = indexOf(id).let { if (it >= 0) rows[it] else null }616617 fun add(row: T) {618 index?.getOrPut(key(row)) { rows.size }619 rows += row620 }621622 // ponytail: a delete shifts the list and drops the index (rebuilt on the next lookup), so bulk deletes stay O(k·n); use replaceAll at restore scale.623 fun remove(id: Long): Boolean = rows.removeAll { key(it) == id }.also { removed -> if (removed) index = null }624625 fun reset(items: List<T>) {626 rows.clear()627 rows.addAll(items)628 index = null629 }630}631632private data class OutboxKey(val kind: Int, val id: Long, val path: String)633634private fun DbOutboxOp.key() = OutboxKey(kind, id, path)635