YokanDatabase.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/YokanDatabase.kt
1package eu.friedcutlet.yokan.database23import eu.friedcutlet.yokan.database.sync.SyncPaths4import kotlinx.coroutines.flow.StateFlow5import kotlinx.serialization.Serializable67@Serializable8data class YokanDatabaseSnapshot(9 val settings: DbSettings,10 val mangas: List<DbManga>,11 val chapters: List<DbChapter>,12 val categories: List<DbCategory>,13 val sources: List<DbSource>,14 val histories: List<DbHistory>,15 val updates: List<DbUpdate>,16 val downloads: List<DbDownload>,17 val tracks: List<DbTrack>,18 val trackPreferences: List<DbTrackPreference>,19 val trackSearches: List<DbTrackSearch>,20 val syncPreferences: List<DbSyncPreference>,21 val changedParts: List<DbChangedPart>,22 val customButtons: List<DbCustomButton>,23 val pageCache: List<DbChapterPageUrls>,24 /** Changes not yet pushed to the hub. */25 val outbox: List<DbOutboxOp> = emptyList(),26)2728class SnapshotReplacementConflictException : IllegalStateException(29 "Database changed while preparing replacement. Retry the operation.",30)3132interface YokanDatabase {33 fun snapshot(): YokanDatabaseSnapshot34 fun snapshots(): StateFlow<YokanDatabaseSnapshot>3536 /** Await writes already queued by a persistent implementation; in-memory backends are immediate. */37 suspend fun awaitPersistence() = Unit3839 /** Owner has stopped producers. Flush and release persistent resources; failure may be retried. */40 suspend fun close() { awaitPersistence() }4142 /** Entry-management apply is enabled only for transactional backends. */43 fun supportsAtomicSnapshotPersistence(): Boolean = false4445 /** Persist and publish a complete snapshot in one backend transaction. */46 suspend fun replaceAllAtomically(47 snapshot: YokanDatabaseSnapshot,48 expectedSnapshot: YokanDatabaseSnapshot? = null,49 removedSourceIds: Set<Long> = emptySet(),50 ) {51 error("ATOMIC_SNAPSHOT_PERSISTENCE_UNAVAILABLE")52 }5354 /** Snapshot transaction originating from remote sync; suppresses local delete recording. */55 suspend fun replaceAllRemoteAtomically(snapshot: YokanDatabaseSnapshot, expectedSnapshot: YokanDatabaseSnapshot?) {56 if (supportsAtomicSnapshotPersistence()) replaceAllAtomically(snapshot, expectedSnapshot)57 else applyRemote { replaceAll(snapshot, expectedSnapshot) }58 }5960 /**61 * Replace the entire database state in one operation: a single snapshot62 * emission and one bulk persistence pass. Restore-scale writes MUST use63 * this — per-row upserts emit a full snapshot copy each, which is64 * quadratic over the library size.65 */66 fun replaceAll(67 snapshot: YokanDatabaseSnapshot,68 expectedSnapshot: YokanDatabaseSnapshot? = null,69 )7071 fun settings(): DbSettings72 fun updateSettings(settings: DbSettings)7374 fun mangas(itemType: DbItemType? = null): List<DbManga>75 fun manga(id: Long): DbManga?76 fun upsertManga(manga: DbManga): DbManga77 fun removeManga(id: Long, recordChange: Boolean = true)7879 fun chapters(mangaId: Long? = null): List<DbChapter>80 fun chapter(id: Long): DbChapter?81 fun upsertChapter(chapter: DbChapter): DbChapter82 fun removeChapter(id: Long, recordChange: Boolean = true)8384 fun categories(itemType: DbItemType? = null): List<DbCategory>85 fun upsertCategory(category: DbCategory): DbCategory86 fun removeCategory(id: Long, recordChange: Boolean = true)8788 fun sources(itemType: DbItemType? = null): List<DbSource>89 fun source(id: Long): DbSource?90 fun upsertSource(source: DbSource): DbSource91 fun removeSource(id: Long)9293 fun histories(): List<DbHistory>94 fun upsertHistory(history: DbHistory): DbHistory95 fun removeHistory(id: Long, recordChange: Boolean = true)9697 fun updates(): List<DbUpdate>98 fun upsertUpdate(update: DbUpdate): DbUpdate99 fun removeUpdate(id: Long, recordChange: Boolean = true)100101 fun downloads(): List<DbDownload>102 fun download(id: Long): DbDownload? = downloads().firstOrNull { it.id == id }103 fun upsertDownload(download: DbDownload): DbDownload104 fun removeDownload(id: Long)105106 fun tracks(mangaId: Long? = null): List<DbTrack>107 fun upsertTrack(track: DbTrack): DbTrack108 fun removeTrack(id: Long, recordChange: Boolean = true)109110 fun trackPreferences(): List<DbTrackPreference>111 fun upsertTrackPreference(preference: DbTrackPreference): DbTrackPreference112113 fun trackSearches(syncId: Int? = null): List<DbTrackSearch>114 fun upsertTrackSearch(search: DbTrackSearch): DbTrackSearch115116 fun syncPreferences(): List<DbSyncPreference>117 fun upsertSyncPreference(preference: DbSyncPreference): DbSyncPreference118119 /** Atomically guard a sync-preference write against a provider/server/account switch. */120 suspend fun upsertSyncPreferenceIf(121 syncId: Long,122 accepts: (DbSyncPreference?) -> Boolean,123 transform: (DbSyncPreference?) -> DbSyncPreference,124 ): Boolean {125 val current = syncPreferences().firstOrNull { it.syncId == syncId }126 if (!accepts(current)) return false127 upsertSyncPreference(transform(current).copy(syncId = syncId))128 return true129 }130131 fun changedParts(): List<DbChangedPart>132 fun recordChange(change: DbChangedPart): DbChangedPart133 fun clearChangedParts()134135 fun customButtons(): List<DbCustomButton>136 fun upsertCustomButton(button: DbCustomButton): DbCustomButton137 fun removeCustomButton(id: Long)138139 fun pageCache(chapterId: Long? = null): List<DbChapterPageUrls>140 fun upsertPageCache(cache: DbChapterPageUrls): DbChapterPageUrls141 fun removePageCache(chapterIds: Collection<Long>)142 fun clearPageCache()143144 // ── hub sync ────────────────────────────────────────────────────────────145146 /** Unpushed hub ops, oldest first. */147 fun outbox(): List<DbOutboxOp> = emptyList()148149 /** Drop ops that were pushed. An op rewritten since (same key, newer seq) is kept. */150 fun removeOutbox(ops: List<DbOutboxOp>) {}151152 /** Reset the hub cursor and discard only operations from older hub epochs (see `hubResync`). */153 suspend fun resyncHub(syncId: Long, epoch: Int): DbSyncPreference154155 /** Writes inside [block] come from the hub and must not be echoed back into the outbox. */156 fun <T> applyRemote(block: () -> T): T = block()157158 /** Coalesce snapshot emissions across many writes into one. */159 fun <T> batch(block: () -> T): T = block()160}161162/** Apply the same synced-content timestamp rule to surviving rows in local snapshot replacements. */163internal fun YokanDatabaseSnapshot.withMangayomiLocalSyncTimestamps(before: YokanDatabaseSnapshot): YokanDatabaseSnapshot {164 if ((before.syncPreferences + syncPreferences).none { it.serverProvider == SyncServerProvider.Mangayomi }) return this165 fun <T> update(rows: List<T>, oldRows: List<T>, id: (T) -> Long, kind: Int, serializer: kotlinx.serialization.KSerializer<T>, at: (T) -> Long, copyAt: (T, Long) -> T): List<T> {166 val oldById = oldRows.associateBy(id)167 return rows.map { row ->168 val old = oldById[id(row)] ?: return@map row169 copyAt(row, SyncPaths.localUpdatedAt(kind, serializer, old, row, at))170 }171 }172 return copy(173 mangas = update(mangas, before.mangas, DbManga::id, SyncPaths.KIND_MANGA, DbManga.serializer(), DbManga::updatedAt) { row, at -> row.copy(updatedAt = at) },174 chapters = update(chapters, before.chapters, DbChapter::id, SyncPaths.KIND_CHAPTER, DbChapter.serializer(), DbChapter::updatedAt) { row, at -> row.copy(updatedAt = at) },175 categories = update(categories, before.categories, DbCategory::id, SyncPaths.KIND_CATEGORY, DbCategory.serializer(), DbCategory::updatedAt) { row, at -> row.copy(updatedAt = at) },176 histories = update(histories, before.histories, DbHistory::id, SyncPaths.KIND_HISTORY, DbHistory.serializer(), DbHistory::updatedAt) { row, at -> row.copy(updatedAt = at) },177 updates = update(updates, before.updates, DbUpdate::id, SyncPaths.KIND_UPDATE, DbUpdate.serializer(), DbUpdate::updatedAt) { row, at -> row.copy(updatedAt = at) },178 tracks = update(tracks, before.tracks, DbTrack::id, SyncPaths.KIND_TRACK, DbTrack.serializer(), DbTrack::updatedAt) { row, at -> row.copy(updatedAt = at) },179 )180}181