package eu.friedcutlet.yokan.database import eu.friedcutlet.yokan.database.sync.SyncPaths import kotlinx.coroutines.flow.StateFlow import kotlinx.serialization.Serializable @Serializable data class YokanDatabaseSnapshot( val settings: DbSettings, val mangas: List, val chapters: List, val categories: List, val sources: List, val histories: List, val updates: List, val downloads: List, val tracks: List, val trackPreferences: List, val trackSearches: List, val syncPreferences: List, val changedParts: List, val customButtons: List, val pageCache: List, /** Changes not yet pushed to the hub. */ val outbox: List = emptyList(), ) class SnapshotReplacementConflictException : IllegalStateException( "Database changed while preparing replacement. Retry the operation.", ) interface YokanDatabase { fun snapshot(): YokanDatabaseSnapshot fun snapshots(): StateFlow /** Await writes already queued by a persistent implementation; in-memory backends are immediate. */ suspend fun awaitPersistence() = Unit /** Owner has stopped producers. Flush and release persistent resources; failure may be retried. */ suspend fun close() { awaitPersistence() } /** Entry-management apply is enabled only for transactional backends. */ fun supportsAtomicSnapshotPersistence(): Boolean = false /** Persist and publish a complete snapshot in one backend transaction. */ suspend fun replaceAllAtomically( snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot? = null, removedSourceIds: Set = emptySet(), ) { error("ATOMIC_SNAPSHOT_PERSISTENCE_UNAVAILABLE") } /** Snapshot transaction originating from remote sync; suppresses local delete recording. */ suspend fun replaceAllRemoteAtomically(snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot?) { if (supportsAtomicSnapshotPersistence()) replaceAllAtomically(snapshot, expectedSnapshot) else applyRemote { replaceAll(snapshot, expectedSnapshot) } } /** * Replace the entire database state in one operation: a single snapshot * emission and one bulk persistence pass. Restore-scale writes MUST use * this — per-row upserts emit a full snapshot copy each, which is * quadratic over the library size. */ fun replaceAll( snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot? = null, ) fun settings(): DbSettings fun updateSettings(settings: DbSettings) fun mangas(itemType: DbItemType? = null): List fun manga(id: Long): DbManga? fun upsertManga(manga: DbManga): DbManga fun removeManga(id: Long, recordChange: Boolean = true) fun chapters(mangaId: Long? = null): List fun chapter(id: Long): DbChapter? fun upsertChapter(chapter: DbChapter): DbChapter fun removeChapter(id: Long, recordChange: Boolean = true) fun categories(itemType: DbItemType? = null): List fun upsertCategory(category: DbCategory): DbCategory fun removeCategory(id: Long, recordChange: Boolean = true) fun sources(itemType: DbItemType? = null): List fun source(id: Long): DbSource? fun upsertSource(source: DbSource): DbSource fun removeSource(id: Long) fun histories(): List fun upsertHistory(history: DbHistory): DbHistory fun removeHistory(id: Long, recordChange: Boolean = true) fun updates(): List fun upsertUpdate(update: DbUpdate): DbUpdate fun removeUpdate(id: Long, recordChange: Boolean = true) fun downloads(): List fun download(id: Long): DbDownload? = downloads().firstOrNull { it.id == id } fun upsertDownload(download: DbDownload): DbDownload fun removeDownload(id: Long) fun tracks(mangaId: Long? = null): List fun upsertTrack(track: DbTrack): DbTrack fun removeTrack(id: Long, recordChange: Boolean = true) fun trackPreferences(): List fun upsertTrackPreference(preference: DbTrackPreference): DbTrackPreference fun trackSearches(syncId: Int? = null): List fun upsertTrackSearch(search: DbTrackSearch): DbTrackSearch fun syncPreferences(): List fun upsertSyncPreference(preference: DbSyncPreference): DbSyncPreference /** Atomically guard a sync-preference write against a provider/server/account switch. */ suspend fun upsertSyncPreferenceIf( syncId: Long, accepts: (DbSyncPreference?) -> Boolean, transform: (DbSyncPreference?) -> DbSyncPreference, ): Boolean { val current = syncPreferences().firstOrNull { it.syncId == syncId } if (!accepts(current)) return false upsertSyncPreference(transform(current).copy(syncId = syncId)) return true } fun changedParts(): List fun recordChange(change: DbChangedPart): DbChangedPart fun clearChangedParts() fun customButtons(): List fun upsertCustomButton(button: DbCustomButton): DbCustomButton fun removeCustomButton(id: Long) fun pageCache(chapterId: Long? = null): List fun upsertPageCache(cache: DbChapterPageUrls): DbChapterPageUrls fun removePageCache(chapterIds: Collection) fun clearPageCache() // ── hub sync ──────────────────────────────────────────────────────────── /** Unpushed hub ops, oldest first. */ fun outbox(): List = emptyList() /** Drop ops that were pushed. An op rewritten since (same key, newer seq) is kept. */ fun removeOutbox(ops: List) {} /** Reset the hub cursor and discard only operations from older hub epochs (see `hubResync`). */ suspend fun resyncHub(syncId: Long, epoch: Int): DbSyncPreference /** Writes inside [block] come from the hub and must not be echoed back into the outbox. */ fun applyRemote(block: () -> T): T = block() /** Coalesce snapshot emissions across many writes into one. */ fun batch(block: () -> T): T = block() } /** Apply the same synced-content timestamp rule to surviving rows in local snapshot replacements. */ internal fun YokanDatabaseSnapshot.withMangayomiLocalSyncTimestamps(before: YokanDatabaseSnapshot): YokanDatabaseSnapshot { if ((before.syncPreferences + syncPreferences).none { it.serverProvider == SyncServerProvider.Mangayomi }) return this fun update(rows: List, oldRows: List, id: (T) -> Long, kind: Int, serializer: kotlinx.serialization.KSerializer, at: (T) -> Long, copyAt: (T, Long) -> T): List { val oldById = oldRows.associateBy(id) return rows.map { row -> val old = oldById[id(row)] ?: return@map row copyAt(row, SyncPaths.localUpdatedAt(kind, serializer, old, row, at)) } } return copy( mangas = update(mangas, before.mangas, DbManga::id, SyncPaths.KIND_MANGA, DbManga.serializer(), DbManga::updatedAt) { row, at -> row.copy(updatedAt = at) }, chapters = update(chapters, before.chapters, DbChapter::id, SyncPaths.KIND_CHAPTER, DbChapter.serializer(), DbChapter::updatedAt) { row, at -> row.copy(updatedAt = at) }, categories = update(categories, before.categories, DbCategory::id, SyncPaths.KIND_CATEGORY, DbCategory.serializer(), DbCategory::updatedAt) { row, at -> row.copy(updatedAt = at) }, histories = update(histories, before.histories, DbHistory::id, SyncPaths.KIND_HISTORY, DbHistory.serializer(), DbHistory::updatedAt) { row, at -> row.copy(updatedAt = at) }, updates = update(updates, before.updates, DbUpdate::id, SyncPaths.KIND_UPDATE, DbUpdate.serializer(), DbUpdate::updatedAt) { row, at -> row.copy(updatedAt = at) }, tracks = update(tracks, before.tracks, DbTrack::id, SyncPaths.KIND_TRACK, DbTrack.serializer(), DbTrack::updatedAt) { row, at -> row.copy(updatedAt = at) }, ) }