package eu.friedcutlet.yokan.database import eu.friedcutlet.yokan.database.sync.SyncClock import eu.friedcutlet.yokan.database.sync.SyncIds import eu.friedcutlet.yokan.database.sync.SyncPaths import eu.friedcutlet.yokan.database.sync.hubResync import eu.friedcutlet.yokan.database.sync.mangayomiDeleteParts import eu.friedcutlet.yokan.util.PlatformLock import eu.friedcutlet.yokan.util.nowMillis import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.serialization.KSerializer import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive /** Chapter page lists kept by [InMemoryYokanDatabase.upsertPageCache]; older ones are refetched (page URLs expire anyway). */ internal const val MAX_PAGE_CACHE = 100 class InMemoryYokanDatabase( initial: YokanDatabaseSnapshot = seedDatabaseSnapshot(), ) : YokanDatabase { private val lock = PlatformLock() private var settings = initial.settings private val mangas = Table(initial.mangas, DbManga::id) private val chapters = Table(initial.chapters, DbChapter::id) private val categories = Table(initial.categories, DbCategory::id) private val sources = Table(initial.sources, DbSource::id) private val histories = Table(initial.histories, DbHistory::id) private val updates = Table(initial.updates, DbUpdate::id) private val downloads = Table(initial.downloads, DbDownload::id) private val tracks = Table(initial.tracks, DbTrack::id) private val trackPreferences = initial.trackPreferences.toMutableList() private val trackSearches = initial.trackSearches.toMutableList() private val syncPreferences = initial.syncPreferences.toMutableList() private val changedParts = Table(initial.changedParts, DbChangedPart::id) private val customButtons = Table(initial.customButtons, DbCustomButton::id) private val pageCache = initial.pageCache.toMutableList() /** Keyed by (kind, id, path) so a rewrite replaces its op in O(1); iteration order is seq order. */ private val outbox = LinkedHashMap() private var outboxSeq = initial.outbox.maxOfOrNull { it.seq } ?: 0L private var suppressOutbox = 0 private var batchDepth = 0 private var newOutboxOps: MutableList? = null private var lastDocValue: Any? = null private var lastDoc: JsonObject? = null private val dirtySnapshotParts = mutableSetOf() init { resetOutbox(initial.outbox) // Epoch-0 ops from before recording required a logged-in hub: no hub ever accepts them // (the first sync seeds full state instead), so they were only growing the database. if (activeHubEpoch() == null) outbox.values.removeAll { it.epoch == 0 } } private val snapshotState = MutableStateFlow(createSnapshot()) override fun snapshot(): YokanDatabaseSnapshot = lock.withLock(::current) override fun snapshots(): StateFlow = snapshotState override fun supportsAtomicSnapshotPersistence(): Boolean = true override suspend fun replaceAllAtomically( snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot?, removedSourceIds: Set, ) { replaceAll(snapshot, expectedSnapshot) } override suspend fun replaceAllRemoteAtomically(snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot?) { applyRemote { replaceAll(snapshot, expectedSnapshot) } } override fun replaceAll( snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot?, ) = lock.withLock { if (expectedSnapshot != null && current() != expectedSnapshot) { throw SnapshotReplacementConflictException() } val before = current() val replacement = if (suppressOutbox > 0) snapshot else snapshot.withMangayomiLocalSyncTimestamps(before) fun MutableList.reset(items: List) { clear() addAll(items) } settings = replacement.settings mangas.reset(replacement.mangas) chapters.reset(replacement.chapters) categories.reset(replacement.categories) sources.reset(replacement.sources) histories.reset(replacement.histories) updates.reset(replacement.updates) downloads.reset(replacement.downloads) tracks.reset(replacement.tracks) trackPreferences.reset(replacement.trackPreferences) trackSearches.reset(replacement.trackSearches) syncPreferences.reset(replacement.syncPreferences) changedParts.reset(replacement.changedParts) customButtons.reset(replacement.customButtons) pageCache.reset(replacement.pageCache) resetOutbox(replacement.outbox) outboxSeq = replacement.outbox.maxOfOrNull { it.seq } ?: 0L if (suppressOutbox == 0) { mangayomiDeleteParts(before, replacement, changedParts.rows.toList(), nowMillis()).forEach(::recordChange) } dirtySnapshotParts.clear() snapshotState.value = createSnapshot() } /** The published snapshot is current whenever nothing is pending, so reads skip the full copy. */ private fun current(): YokanDatabaseSnapshot = if (dirtySnapshotParts.isEmpty()) snapshotState.value else createSnapshot() private fun createSnapshot(): YokanDatabaseSnapshot = YokanDatabaseSnapshot( settings = settings, mangas = mangas.rows.toList(), chapters = chapters.rows.toList(), categories = categories.rows.toList(), sources = sources.rows.toList(), histories = histories.rows.toList(), updates = updates.rows.toList(), downloads = downloads.rows.toList(), tracks = tracks.rows.toList(), trackPreferences = trackPreferences.toList(), trackSearches = trackSearches.toList(), syncPreferences = syncPreferences.toList(), changedParts = changedParts.rows.toList(), customButtons = customButtons.rows.toList(), pageCache = pageCache.toList(), outbox = outbox.values.toList(), ) override fun settings(): DbSettings = lock.withLock { settings } override fun updateSettings(settings: DbSettings) = lock.withLock { val before = this.settings this.settings = settings if (before != settings) { recordDoc(SyncPaths.KIND_SETTINGS, SyncPaths.SETTINGS_ID, before, settings, DbSettings.serializer()) } emitSnapshot(SnapshotPart.Settings) } override fun mangas(itemType: DbItemType?): List = lock.withLock { mangas.rows.filter { itemType == null || it.itemType == itemType } } override fun manga(id: Long): DbManga? = lock.withLock { mangas[id] } override fun upsertManga(manga: DbManga): DbManga = lock.withLock { val identified = if (manga.id == 0L) assignId(manga) else manga val old = mangas[identified.id] val value = localTimestamp(identified, old, SyncPaths.KIND_MANGA, DbManga.serializer(), DbManga::updatedAt) { row, at -> row.copy(updatedAt = at) } upsert(mangas, value, SyncPaths.KIND_MANGA, DbManga.serializer()).also { emitSnapshot(SnapshotPart.Mangas) } } override fun removeManga(id: Long, recordChange: Boolean) = lock.withLock { if (mangas.remove(id) && recordChange) { recordDelete(SyncPaths.KIND_MANGA, id); recordMangayomiDelete(SyncPaths.KIND_MANGA, id, DbActionType.RemoveItem) } emitSnapshot(SnapshotPart.Mangas) } override fun chapters(mangaId: Long?): List = lock.withLock { chapters.rows.filter { mangaId == null || it.mangaId == mangaId } } override fun chapter(id: Long): DbChapter? = lock.withLock { chapters[id] } override fun upsertChapter(chapter: DbChapter): DbChapter = lock.withLock { val identified = if (chapter.id == 0L) assignId(chapter) else chapter val old = chapters[identified.id] val value = localTimestamp(identified, old, SyncPaths.KIND_CHAPTER, DbChapter.serializer(), DbChapter::updatedAt) { row, at -> row.copy(updatedAt = at) } upsert(chapters, value, SyncPaths.KIND_CHAPTER, DbChapter.serializer()).also { emitSnapshot(SnapshotPart.Chapters) } } override fun removeChapter(id: Long, recordChange: Boolean) = lock.withLock { if (chapters.remove(id) && recordChange) { recordDelete(SyncPaths.KIND_CHAPTER, id); recordMangayomiDelete(SyncPaths.KIND_CHAPTER, id, DbActionType.RemoveChapter) } if (pageCache.removeAll { it.chapterId == id }) dirtySnapshotParts += SnapshotPart.PageCache emitSnapshot(SnapshotPart.Chapters) } override fun categories(itemType: DbItemType?): List = lock.withLock { categories.rows.filter { itemType == null || it.forItemType == itemType }.sortedBy { it.position ?: 0 } } override fun upsertCategory(category: DbCategory): DbCategory = lock.withLock { val identified = if (category.id == 0L) assignId(category) else category val old = categories[identified.id] val value = localTimestamp(identified, old, SyncPaths.KIND_CATEGORY, DbCategory.serializer(), DbCategory::updatedAt) { row, at -> row.copy(updatedAt = at) } upsert(categories, value, SyncPaths.KIND_CATEGORY, DbCategory.serializer()).also { emitSnapshot(SnapshotPart.Categories) } } override fun removeCategory(id: Long, recordChange: Boolean) = lock.withLock { if (categories.remove(id) && recordChange) { recordDelete(SyncPaths.KIND_CATEGORY, id); recordMangayomiDelete(SyncPaths.KIND_CATEGORY, id, DbActionType.RemoveCategory) } emitSnapshot(SnapshotPart.Categories) } override fun sources(itemType: DbItemType?): List = lock.withLock { // Strict item-type match. Local sources used to leak into every tab // via `|| it.isLocal`, which mixed Anime archives into the Manga // browse tab. If a user has local archives for multiple item types, // they need separate local sources per type. sources.rows.filter { itemType == null || it.itemType == itemType } } override fun source(id: Long): DbSource? = lock.withLock { sources[id] } override fun upsertSource(source: DbSource): DbSource = lock.withLock { upsert(sources, source).also { emitSnapshot(SnapshotPart.Sources) } } override fun removeSource(id: Long) = lock.withLock { batch { sources.remove(id) recordChange(DbChangedPart(actionType = DbActionType.RemoveExtension, isarId = id, data = "", clientDate = nowMillis())) emitSnapshot(SnapshotPart.Sources) } } override fun histories(): List = lock.withLock { histories.rows.toList() } override fun upsertHistory(history: DbHistory): DbHistory = lock.withLock { val identified = if (history.id == 0L) assignId(history) else history val old = histories[identified.id] val value = localTimestamp(identified, old, SyncPaths.KIND_HISTORY, DbHistory.serializer(), DbHistory::updatedAt) { row, at -> row.copy(updatedAt = at) } upsert(histories, value, SyncPaths.KIND_HISTORY, DbHistory.serializer()).also { emitSnapshot(SnapshotPart.Histories) } } override fun removeHistory(id: Long, recordChange: Boolean) = lock.withLock { if (histories.remove(id) && recordChange) { recordDelete(SyncPaths.KIND_HISTORY, id); recordMangayomiDelete(SyncPaths.KIND_HISTORY, id, DbActionType.RemoveHistory) } emitSnapshot(SnapshotPart.Histories) } override fun updates(): List = lock.withLock { updates.rows.toList() } override fun upsertUpdate(update: DbUpdate): DbUpdate = lock.withLock { val identified = if (update.id == 0L) assignId(update) else update val old = updates[identified.id] val value = localTimestamp(identified, old, SyncPaths.KIND_UPDATE, DbUpdate.serializer(), DbUpdate::updatedAt) { row, at -> row.copy(updatedAt = at) } upsert(updates, value, SyncPaths.KIND_UPDATE, DbUpdate.serializer()).also { emitSnapshot(SnapshotPart.Updates) } } override fun removeUpdate(id: Long, recordChange: Boolean) = lock.withLock { if (updates.remove(id) && recordChange) { recordDelete(SyncPaths.KIND_UPDATE, id); recordMangayomiDelete(SyncPaths.KIND_UPDATE, id, DbActionType.RemoveUpdate) } emitSnapshot(SnapshotPart.Updates) } override fun downloads(): List = lock.withLock { downloads.rows.toList() } override fun download(id: Long): DbDownload? = lock.withLock { downloads[id] } override fun upsertDownload(download: DbDownload): DbDownload = lock.withLock { upsert(downloads, download).also { emitSnapshot(SnapshotPart.Downloads) } } override fun removeDownload(id: Long) = lock.withLock { downloads.remove(id) emitSnapshot(SnapshotPart.Downloads) } override fun tracks(mangaId: Long?): List = lock.withLock { tracks.rows.filter { mangaId == null || it.mangaId == mangaId } } override fun upsertTrack(track: DbTrack): DbTrack = lock.withLock { val identified = if (track.id == 0L) assignId(track) else track val old = tracks[identified.id] val value = localTimestamp(identified, old, SyncPaths.KIND_TRACK, DbTrack.serializer(), DbTrack::updatedAt) { row, at -> row.copy(updatedAt = at) } upsert(tracks, value, SyncPaths.KIND_TRACK, DbTrack.serializer()).also { emitSnapshot(SnapshotPart.Tracks) } } override fun removeTrack(id: Long, recordChange: Boolean) = lock.withLock { if (tracks.remove(id) && recordChange) { recordDelete(SyncPaths.KIND_TRACK, id); recordMangayomiDelete(SyncPaths.KIND_TRACK, id, DbActionType.RemoveTrack) } emitSnapshot(SnapshotPart.Tracks) } override fun trackPreferences(): List = lock.withLock { trackPreferences.toList() } override fun upsertTrackPreference(preference: DbTrackPreference): DbTrackPreference = lock.withLock { upsertNullableKey(trackPreferences, preference, DbTrackPreference::syncId).also { emitSnapshot(SnapshotPart.TrackPreferences) } } override fun trackSearches(syncId: Int?): List = lock.withLock { trackSearches.filter { syncId == null || it.syncId == syncId } } override fun upsertTrackSearch(search: DbTrackSearch): DbTrackSearch = lock.withLock { upsertNullableKey(trackSearches, search, DbTrackSearch::id).also { emitSnapshot(SnapshotPart.TrackSearches) } } override fun syncPreferences(): List = lock.withLock { syncPreferences.toList() } override fun upsertSyncPreference(preference: DbSyncPreference): DbSyncPreference = lock.withLock { upsertNullableKey(syncPreferences, preference, DbSyncPreference::syncId).also { emitSnapshot(SnapshotPart.SyncPreferences) } } override suspend fun upsertSyncPreferenceIf( syncId: Long, accepts: (DbSyncPreference?) -> Boolean, transform: (DbSyncPreference?) -> DbSyncPreference, ): Boolean = lock.withLock { val current = syncPreferences.firstOrNull { it.syncId == syncId } if (!accepts(current)) return@withLock false val updated = transform(current).copy(syncId = syncId) upsertNullableKey(syncPreferences, updated, DbSyncPreference::syncId) emitSnapshot(SnapshotPart.SyncPreferences) true } override fun changedParts(): List = lock.withLock { changedParts.rows.toList() } override fun recordChange(change: DbChangedPart): DbChangedPart = lock.withLock { val used = changedParts.rows.mapTo(HashSet(), DbChangedPart::id) var id = change.id.takeIf { it > 0 && it !in used } ?: SyncIds.random() while (id in used) id = SyncIds.random() upsert(changedParts, change.copy(id = id)).also { emitSnapshot(SnapshotPart.ChangedParts) } } override fun clearChangedParts() = lock.withLock { changedParts.reset(emptyList()) emitSnapshot(SnapshotPart.ChangedParts) } override fun customButtons(): List = lock.withLock { customButtons.rows.sortedBy { it.position } } override fun upsertCustomButton(button: DbCustomButton): DbCustomButton = lock.withLock { upsert(customButtons, button).also { emitSnapshot(SnapshotPart.CustomButtons) } } override fun removeCustomButton(id: Long) = lock.withLock { customButtons.remove(id) emitSnapshot(SnapshotPart.CustomButtons) } override fun pageCache(chapterId: Long?): List = lock.withLock { pageCache.filter { chapterId == null || it.chapterId == chapterId } } override fun upsertPageCache(cache: DbChapterPageUrls): DbChapterPageUrls = lock.withLock { cache.chapterId?.let { id -> pageCache.removeAll { it.chapterId == id } } pageCache += cache // ponytail: evicts by write order only; track read recency if the offline reader needs older lists. if (pageCache.size > MAX_PAGE_CACHE) pageCache.subList(0, pageCache.size - MAX_PAGE_CACHE).clear() emitSnapshot(SnapshotPart.PageCache) cache } override fun removePageCache(chapterIds: Collection) { lock.withLock { if (pageCache.removeAll { it.chapterId in chapterIds }) emitSnapshot(SnapshotPart.PageCache) } } override fun clearPageCache() = lock.withLock { pageCache.clear() emitSnapshot(SnapshotPart.PageCache) } // ── hub sync ──────────────────────────────────────────────────────────── override fun outbox(): List = lock.withLock { outbox.values.toList() } /** Runs [block] and also returns the outbox ops it appended, so the Room layer persists exactly those. */ internal fun recordingOutbox(block: () -> T): Pair> = lock.withLock { val outer = newOutboxOps val ops = ArrayList() newOutboxOps = ops try { block() to ops } finally { newOutboxOps = outer outer?.addAll(ops) } } override fun removeOutbox(ops: List) = lock.withLock { if (ops.isEmpty()) return@withLock for (op in ops) { val key = op.key() if (outbox[key]?.seq == op.seq) outbox.remove(key) } emitSnapshot(SnapshotPart.Outbox) } override suspend fun resyncHub(syncId: Long, epoch: Int): DbSyncPreference = lock.withLock { val current = syncPreferences.firstOrNull { it.syncId == syncId } ?: DbSyncPreference(syncId = syncId) val (updated, dropBefore) = current.hubResync(epoch) upsertNullableKey(syncPreferences, updated, DbSyncPreference::syncId) if (dropBefore != null) outbox.values.removeAll { it.epoch < dropBefore } dirtySnapshotParts += SnapshotPart.SyncPreferences dirtySnapshotParts += SnapshotPart.Outbox publishDirtySnapshot() updated } override fun applyRemote(block: () -> T): T = lock.withLock { suppressOutbox++ try { block() } finally { suppressOutbox-- } } override fun batch(block: () -> T): T = lock.withLock { batchDepth++ try { block() } finally { batchDepth-- if (batchDepth == 0) publishDirtySnapshot() } } /** * Record the path-level difference between two versions of a row. Nothing is recorded while * no hub is logged in: the first sync seeds the hub with full local state, not the outbox. */ private fun recordDoc(kind: Int, id: Long, before: T?, after: T, serializer: KSerializer) { if (suppressOutbox > 0) return val epoch = activeHubEpoch() ?: return val beforeDoc = before?.let { docOf(kind, serializer, it) } record(kind, id, SyncPaths.diff(kind, beforeDoc, docOf(kind, serializer, after)), epoch) } private fun recordDelete(kind: Int, id: Long) { if (suppressOutbox > 0) return val epoch = activeHubEpoch() ?: return record(kind, id, listOf(SyncPaths.PathChange(SyncPaths.DELETED, JsonPrimitive(true))), epoch) } private fun record(kind: Int, id: Long, changes: List, epoch: Int) { for (change in changes) { val op = DbOutboxOp( kind = kind, id = id, path = change.path, value = change.value?.toString(), hlc = SyncClock.tick(), seq = ++outboxSeq, epoch = epoch, ) putOutbox(op) newOutboxOps?.add(op) } if (changes.isNotEmpty()) dirtySnapshotParts += SnapshotPart.Outbox } /** Wire doc of [value]. The last row's doc is kept, so rewriting a row (or settings) encodes it once. */ private fun docOf(kind: Int, serializer: KSerializer, value: T): JsonObject { val cached = lastDoc if (cached != null && lastDocValue === value) return cached return SyncPaths.doc(kind, serializer, value).also { lastDocValue = value lastDoc = it } } private fun putOutbox(op: DbOutboxOp) { val key = op.key() outbox.remove(key) outbox[key] = op } private fun resetOutbox(ops: List) { outbox.clear() ops.sortedBy { it.seq }.forEach(::putOutbox) } private fun activeHubEpoch(): Int? = SyncPaths.activeHubEpoch(syncPreferences) private fun localTimestamp( incoming: T, previous: T?, kind: Int, serializer: KSerializer, timestamp: (T) -> Long, copyTimestamp: (T, Long) -> T, ): T { // Only Mangayomi's whole-row LWW needs this; Hub merges per path and must not see updatedAt churn. if (suppressOutbox > 0 || syncPreferences.none { it.serverProvider == SyncServerProvider.Mangayomi }) return incoming return copyTimestamp(incoming, SyncPaths.localUpdatedAt(kind, serializer, previous, incoming, timestamp)) } private fun recordMangayomiDelete(kind: Int, id: Long, action: DbActionType) { if (suppressOutbox > 0) return mangayomiDeleteParts(kind, id, action, syncPreferences.toList(), changedParts.rows.toList(), nowMillis()).forEach(::recordChange) } private fun emitSnapshot(part: SnapshotPart) { dirtySnapshotParts += part if (batchDepth > 0) { return } publishDirtySnapshot() } private fun publishDirtySnapshot() { if (dirtySnapshotParts.isEmpty()) return var next = snapshotState.value dirtySnapshotParts.forEach { part -> next = when (part) { SnapshotPart.Settings -> next.copy(settings = settings) SnapshotPart.Mangas -> next.copy(mangas = mangas.rows.toList()) SnapshotPart.Chapters -> next.copy(chapters = chapters.rows.toList()) SnapshotPart.Categories -> next.copy(categories = categories.rows.toList()) SnapshotPart.Sources -> next.copy(sources = sources.rows.toList()) SnapshotPart.Histories -> next.copy(histories = histories.rows.toList()) SnapshotPart.Updates -> next.copy(updates = updates.rows.toList()) SnapshotPart.Downloads -> next.copy(downloads = downloads.rows.toList()) SnapshotPart.Tracks -> next.copy(tracks = tracks.rows.toList()) SnapshotPart.TrackPreferences -> next.copy(trackPreferences = trackPreferences.toList()) SnapshotPart.TrackSearches -> next.copy(trackSearches = trackSearches.toList()) SnapshotPart.SyncPreferences -> next.copy(syncPreferences = syncPreferences.toList()) SnapshotPart.ChangedParts -> next.copy(changedParts = changedParts.rows.toList()) SnapshotPart.CustomButtons -> next.copy(customButtons = customButtons.rows.toList()) SnapshotPart.PageCache -> next.copy(pageCache = pageCache.toList()) SnapshotPart.Outbox -> next.copy(outbox = outbox.values.toList()) } } dirtySnapshotParts.clear() snapshotState.value = next } private enum class SnapshotPart { Settings, Mangas, Chapters, Categories, Sources, Histories, Updates, Downloads, Tracks, TrackPreferences, TrackSearches, SyncPreferences, ChangedParts, CustomButtons, PageCache, Outbox, } private fun upsert( table: Table, item: T, kind: Int = 0, serializer: KSerializer? = null, ): T { val normalized = if (table.key(item) == 0L) assignId(item) else item val id = table.key(normalized) val index = table.indexOf(id) val previous = if (index >= 0) table.rows[index] else null if (index >= 0) { table.rows[index] = normalized } else { table.add(normalized) } if (serializer != null && previous != normalized) recordDoc(kind, id, previous, normalized, serializer) return normalized } private fun upsertNullableKey(items: MutableList, item: T, key: (T) -> K?): T { val itemKey = key(item) val index = if (itemKey == null) -1 else items.indexOfFirst { key(it) == itemKey } if (index >= 0) { items[index] = item } else { items += item } return item } /** * Synced entities get stable ids derived from their natural key ([SyncIds]) so devices agree * on identity without coordination; local-only tables keep a plain counter. */ @Suppress("UNCHECKED_CAST") private fun assignId(item: T): T = when (item) { is DbManga -> item.copy(id = SyncIds.forManga(item) ?: SyncIds.random()) is DbChapter -> item.copy(id = SyncIds.forChapter(item) ?: SyncIds.random()) is DbCategory -> item.copy(id = SyncIds.random()) is DbHistory -> item.copy(id = SyncIds.forHistory(item) ?: SyncIds.random()) is DbUpdate -> item.copy(id = SyncIds.forUpdate(item) ?: SyncIds.random()) is DbTrack -> item.copy(id = SyncIds.forTrack(item) ?: SyncIds.random()) is DbSource -> item.copy(id = nextId(sources.rows, DbSource::id)) is DbDownload -> item.copy(id = nextId(downloads.rows, DbDownload::id)) is DbChangedPart -> item.copy(id = nextId(changedParts.rows, DbChangedPart::id)) is DbCustomButton -> item.copy(id = nextId(customButtons.rows, DbCustomButton::id)) else -> item } as T private fun nextId(items: List, key: (T) -> Long): Long = (items.maxOfOrNull(key) ?: 0L) + 1L } /** Rows in insertion order plus a lazily rebuilt id → first-row index, so point lookups and upserts are O(1). */ private class Table(initial: List, val key: (T) -> Long) { val rows = ArrayList(initial) private var index: HashMap? = null fun indexOf(id: Long): Int { val map = index ?: HashMap(rows.size).also { built -> rows.forEachIndexed { position, row -> built.getOrPut(key(row)) { position } } index = built } return map[id] ?: -1 } operator fun get(id: Long): T? = indexOf(id).let { if (it >= 0) rows[it] else null } fun add(row: T) { index?.getOrPut(key(row)) { rows.size } rows += row } // 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. fun remove(id: Long): Boolean = rows.removeAll { key(it) == id }.also { removed -> if (removed) index = null } fun reset(items: List) { rows.clear() rows.addAll(items) index = null } } private data class OutboxKey(val kind: Int, val id: Long, val path: String) private fun DbOutboxOp.key() = OutboxKey(kind, id, path)