Yokan / rebuild
Course 1 8624561

SyncPaths.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncPaths.kt

implementation315 lines
1package eu.friedcutlet.yokan.database.sync23import eu.friedcutlet.yokan.database.DbCategory4import eu.friedcutlet.yokan.database.DbChapter5import eu.friedcutlet.yokan.database.DbHistory6import eu.friedcutlet.yokan.database.DbManga7import eu.friedcutlet.yokan.database.DbOutboxOp8import eu.friedcutlet.yokan.database.DbPersonalReaderMode9import eu.friedcutlet.yokan.database.DbSettings10import eu.friedcutlet.yokan.database.DbSyncPreference11import eu.friedcutlet.yokan.database.SyncServerProvider12import eu.friedcutlet.yokan.database.DbTrack13import eu.friedcutlet.yokan.database.DbUpdate14import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot15import eu.friedcutlet.yokan.util.nowMillis16import kotlinx.serialization.KSerializer17import kotlinx.serialization.json.Json18import kotlinx.serialization.json.JsonArray19import kotlinx.serialization.json.JsonElement20import kotlinx.serialization.json.JsonNull21import kotlinx.serialization.json.JsonObject22import kotlinx.serialization.json.JsonPrimitive23import kotlinx.serialization.json.buildJsonObject24import kotlinx.serialization.json.encodeToJsonElement25import kotlinx.serialization.json.jsonObject26import kotlinx.serialization.json.jsonPrimitive2728/**29 * Wire shape of a synced entity and the path-level diff that feeds the outbox.30 *31 * The hub stores each entity as a JSON object and merges per *path*: a top-level field, or32 * `field.key` for keyed collections. So a `List<DbPersonalReaderMode>` travels as33 * `{ "<mangaId>": {...element...} }` and a manga's `categories: List<Long>` as `{ "<id>": true }`.34 * `yokan-hub/src/snapshots.rs::to_backup_snapshot` performs the inverse on export.35 */36object SyncPaths {37    const val KIND_CATEGORY = 138    const val KIND_MANGA = 239    const val KIND_CHAPTER = 340    const val KIND_TRACK = 441    const val KIND_HISTORY = 542    const val KIND_UPDATE = 643    const val KIND_SETTINGS = 744    const val SETTINGS_ID = 1L45    const val DELETED = "_deleted"4647    val json: Json = Json {48        encodeDefaults = true49        explicitNulls = false50        ignoreUnknownKeys = true51    }5253    /** `value == null` removes the path. */54    data class PathChange(val path: String, val value: JsonElement?)5556    /**57     * The one list of device-local [DbSettings] fields: never pushed through sync and never58     * overwritten by a restored backup (see [preserveDeviceLocalSettings]). Paths, loopback59     * endpoints and credentials only make sense on the machine that set them.60     */61    private val settingsDeviceLocal = setOf(62        "id", "syncIdentityVersion",63        // device paths and processes64        "localFolders", "namedLocalFolders", "downloadLocalFolderName", "askDownloadDestination",65        "downloadLocation", "autoBackupLocation", "themeSeedImagePath", "androidProxyServer", "cloudflareBypassProxyUrl",66        "jrePath", "extensionServerPath", "btServerAddress", "btServerPort", "desktopCloseToTray", "desktopLaunchAtLogin",67        "customHubServers",68        // secrets and caches69        "cookiesList", "metadataServerToken", "updateErrors",70        // Discovery layout, installed-source references and API credentials belong to this device.71        "features",72        // debugging73        "enableLogs", "enableFileLogging", "developerMode",74        // Title-owned preferences need explicit owner remapping before hub protocol support.75        "chapterReleasePreferences",76        "automaticReaderLayout", "automaticReaderLayouts",77        "readerHoldToScroll",78        // E-ink display mode describes this device's screen.79        "einkMode", "einkPreset", "einkRefreshEveryPages", "einkOptimizeDownloads",80    )8182    private val excludedByKind: Map<Int, Set<String>> = mapOf(83        KIND_MANGA to setOf("id", "customCoverImage", "privateNote"),84        // Only downloads set downloadSize; with it, archivePath is this device's download folder (see hasDownloadMark).85        KIND_CHAPTER to setOf("id", "downloadSize"),86        KIND_SETTINGS to settingsDeviceLocal,87    )8889    fun excluded(kind: Int): Set<String> = excludedByKind[kind] ?: setOf("id")9091    private const val SOURCE_PREF_KEY = "sourceId+key"9293    private val settingsKeyed: Map<String, String> = mapOf(94        "sortChapterList" to "mangaId",95        "chapterFilterDownloadedList" to "mangaId",96        "chapterFilterUnreadList" to "mangaId",97        "chapterFilterBookmarkedList" to "mangaId",98        "chapterPageIndexList" to "chapterId",99        "personalReaderModeList" to "mangaId",100        "filterScanlatorList" to "mangaId",101        "personalPageModeList" to "mangaId",102        "autoScrollPages" to "mangaId",103        "titleMetadata" to "mangaId",104        "sourcePreferences" to SOURCE_PREF_KEY,105    )106107    /** Fields stored as objects keyed by an element field, so two devices can edit different entries. */108    fun keyedFields(kind: Int): Map<String, String> = if (kind == KIND_SETTINGS) settingsKeyed else emptyMap()109110    /** `List<Long>` fields stored as `{ "<id>": true }` (a set with per-element clocks). */111    fun idSetFields(kind: Int): Set<String> = if (kind == KIND_MANGA) setOf("categories") else emptySet()112113    private fun elementKey(spec: String, element: JsonObject): String? = if (spec == SOURCE_PREF_KEY) {114        val s = element["sourceId"]?.jsonPrimitive?.content ?: return null115        val k = element["key"]?.jsonPrimitive?.content ?: return null116        "$s:$k"117    } else {118        element[spec]?.jsonPrimitive?.content119    }120121    fun <T> doc(kind: Int, serializer: KSerializer<T>, value: T): JsonObject =122        toDoc(kind, json.encodeToJsonElement(serializer, value).jsonObject)123124    /** Content equality used for local timestamps: excludes device-local fields and updatedAt itself. */125    fun <T> syncContentChanged(kind: Int, serializer: KSerializer<T>, before: T, after: T): Boolean {126        val old = doc(kind, serializer, before).filterKeys { it != "updatedAt" }127        val next = doc(kind, serializer, after).filterKeys { it != "updatedAt" }128        return old != next129    }130131    fun <T> localUpdatedAt(kind: Int, serializer: KSerializer<T>, previous: T?, incoming: T, timestamp: (T) -> Long): Long {132        val incomingAt = timestamp(incoming)133        if (previous == null) return maxOf(nowMillis(), incomingAt)134        if (!syncContentChanged(kind, serializer, previous, incoming)) return timestamp(previous)135        val priorAt = timestamp(previous)136        val nextAt = if (priorAt == Long.MAX_VALUE) priorAt else priorAt + 1137        return maxOf(nowMillis(), incomingAt, nextAt)138    }139140    fun toDoc(kind: Int, obj: JsonObject): JsonObject {141        val excluded = excluded(kind)142        val keyed = keyedFields(kind)143        val idSets = idSetFields(kind)144        return buildJsonObject {145            for ((k, v) in obj) {146                if (k in excluded || (kind == KIND_SETTINGS && k == "home")) continue147                if (kind == KIND_CHAPTER && k == "archivePath" && obj.hasDownloadMark()) {148                    // Local-library chapters keep syncing their (virtual) archivePath; a download's path stays here.149                    put(k, JsonPrimitive(""))150                    continue151                }152                when {153                    k in idSets && v is JsonArray -> put(k, buildJsonObject { v.forEach { put(it.jsonPrimitive.content, JsonPrimitive(true)) } })154                    k in keyed && v is JsonArray -> put(155                        k,156                        buildJsonObject {157                            val spec = keyed.getValue(k)158                            v.forEach { el ->159                                val o = el as? JsonObject ?: return@forEach160                                elementKey(spec, o)?.let { put(it, o) }161                            }162                        },163                    )164                    else -> put(k, v)165                }166            }167        }168    }169170    fun fromDoc(kind: Int, doc: JsonObject): JsonObject {171        val keyed = keyedFields(kind)172        val idSets = idSetFields(kind)173        return buildJsonObject {174            for ((k, v) in doc) {175                if (k == DELETED) continue176                when {177                    k in idSets && v is JsonObject -> put(k, JsonArray(v.keys.mapNotNull { it.toLongOrNull() }.sorted().map(::JsonPrimitive)))178                    k in keyed && v is JsonObject -> put(k, JsonArray(v.values.toList()))179                    else -> put(k, v)180                }181            }182        }183    }184185    /** Path-level difference between two docs; keyed and id-set fields diff one level down. */186    fun diff(kind: Int, before: JsonObject?, after: JsonObject): List<PathChange> {187        val nested = keyedFields(kind).keys + idSetFields(kind)188        val out = ArrayList<PathChange>()189        for (k in LinkedHashSet(before?.keys.orEmpty() + after.keys)) {190            val a = before?.get(k)191            val b = after[k]192            if (a == b) continue193            if (k in nested && (a == null || a is JsonObject) && (b == null || b is JsonObject)) {194                val ao = a195                val bo = b196                for (sub in LinkedHashSet(ao?.keys.orEmpty() + bo?.keys.orEmpty())) {197                    val x = ao?.get(sub)198                    val y = bo?.get(sub)199                    if (x != y) out += PathChange("$k.$sub", y)200                }201            } else {202                out += PathChange(k, b)203            }204        }205        return out206    }207208    /**209     * Merge an incoming hub doc onto the local object: every synced field comes from the hub210     * (absent means removed), excluded fields keep their local value even when an older client211     * pushed them to the hub, `id` is the entity key. A chapter keeps this device's download212     * folder, and a download folder pushed from another device is dropped.213     */214    fun applyIncoming(kind: Int, local: JsonObject?, incomingDoc: JsonObject, id: Long): JsonObject {215        val excluded = excluded(kind)216        val incoming = fromDoc(kind, incomingDoc)217        return buildJsonObject {218            local?.forEach { (k, v) -> if (k in excluded && k != "id") put(k, v) }219            incoming.forEach { (k, v) -> if (k !in excluded && !(kind == KIND_SETTINGS && k == "home")) put(k, v) }220            if (kind == KIND_CHAPTER) {221                when {222                    local?.hasDownloadMark() == true -> put("archivePath", local["archivePath"] ?: JsonPrimitive(""))223                    incoming.hasDownloadMark() -> put("archivePath", JsonPrimitive(""))224                }225            }226            put("id", JsonPrimitive(id))227        }228    }229230    private fun JsonObject.hasDownloadMark(): Boolean = this["downloadSize"].let { it != null && it !is JsonNull }231232    /** Put this device's still-pending values for their paths back on top of an incoming doc. */233    fun overlay(doc: JsonObject, pending: List<DbOutboxOp>): JsonObject {234        if (pending.isEmpty()) return doc235        val top = LinkedHashMap<String, JsonElement>(doc)236        for (op in pending) {237            if (op.path == DELETED) continue238            val value = op.value?.let(json::parseToJsonElement)239            val dot = op.path.indexOf('.')240            if (dot < 0) {241                if (value == null || value is JsonNull) top.remove(op.path) else top[op.path] = value242            } else {243                val field = op.path.substring(0, dot)244                val sub = op.path.substring(dot + 1)245                val inner = LinkedHashMap<String, JsonElement>((top[field] as? JsonObject).orEmpty())246                if (value == null || value is JsonNull) inner.remove(sub) else inner[sub] = value247                top[field] = JsonObject(inner)248            }249        }250        return JsonObject(top)251    }252253    /** Every synced entity of [s] (restricted to [kinds]) as `(kind, id, doc)`. */254    fun docs(s: YokanDatabaseSnapshot, kinds: Set<Int> = ALL_KINDS): Sequence<Triple<Int, Long, JsonObject>> {255        fun <T> List<T>.docs(kind: Int, serializer: KSerializer<T>, id: (T) -> Long) =256            if (kind in kinds) asSequence().map { Triple(kind, id(it), doc(kind, serializer, it)) } else emptySequence()257        return s.categories.docs(KIND_CATEGORY, DbCategory.serializer(), DbCategory::id) +258            s.mangas.docs(KIND_MANGA, DbManga.serializer(), DbManga::id) +259            s.chapters.docs(KIND_CHAPTER, DbChapter.serializer(), DbChapter::id) +260            s.tracks.docs(KIND_TRACK, DbTrack.serializer(), DbTrack::id) +261            s.histories.docs(KIND_HISTORY, DbHistory.serializer(), DbHistory::id) +262            s.updates.docs(KIND_UPDATE, DbUpdate.serializer(), DbUpdate::id) +263            listOf(s.settings).docs(KIND_SETTINGS, DbSettings.serializer()) { SETTINGS_ID }264    }265266    val ALL_KINDS: Set<Int> = (KIND_CATEGORY..KIND_SETTINGS).toSet()267268    /**269     * Epoch new outbox ops belong to: the logged-in hub's (0 until negotiated), or null while no hub270     * is active. Nothing is recorded then; the first sync seeds the hub with full local state.271     */272    fun activeHubEpoch(prefs: List<DbSyncPreference>): Int? = prefs.firstOrNull {273        it.serverProvider == SyncServerProvider.YokanHub && it.syncOn && !it.authToken.isNullOrBlank() &&274            !it.server.isNullOrBlank() && !it.server.startsWith("cloud://")275    }?.hubEpoch276277    /**278     * [after]'s outbox extended with every path that differs from [before], each with a fresh clock,279     * so a wholesale replacement (backup restore) reaches the hub like ordinary edits and wins over280     * what the hub had. Entities missing from [after] are sent as deletes. Without an active hub281     * nothing is added, as for ordinary edits.282     */283    fun outboxForReplacement(before: YokanDatabaseSnapshot, after: YokanDatabaseSnapshot): List<DbOutboxOp> {284        val epoch = activeHubEpoch(after.syncPreferences) ?: return after.outbox285        val old = docs(before).associate { (kind, id, doc) -> (kind to id) to doc }.toMutableMap()286        var seq = after.outbox.maxOfOrNull { it.seq } ?: 0L287        val added = ArrayList<DbOutboxOp>()288        fun add(kind: Int, id: Long, change: PathChange) {289            added += DbOutboxOp(kind = kind, id = id, path = change.path, value = change.value?.toString(), hlc = SyncClock.tick(), seq = ++seq, epoch = epoch)290        }291        for ((kind, id, doc) in docs(after)) {292            for (change in diff(kind, old.remove(kind to id), doc)) add(kind, id, change)293        }294        for ((key, _) in old) add(key.first, key.second, PathChange(DELETED, JsonPrimitive(true)))295        if (added.isEmpty()) return after.outbox296        val replaced = added.mapTo(HashSet()) { Triple(it.kind, it.id, it.path) }297        return after.outbox.filterNot { Triple(it.kind, it.id, it.path) in replaced } + added298    }299}300301/**302 * [incoming] settings (e.g. from a restored backup) with every device-local field303 * ([SyncPaths.excluded] for [SyncPaths.KIND_SETTINGS]) kept from [current].304 */305fun preserveDeviceLocalSettings(current: DbSettings, incoming: DbSettings): DbSettings {306    val json = SyncPaths.json307    val local = json.encodeToJsonElement(DbSettings.serializer(), current).jsonObject308    val merged = json.encodeToJsonElement(DbSettings.serializer(), incoming).jsonObject.toMutableMap()309    for (key in SyncPaths.excluded(SyncPaths.KIND_SETTINGS)) {310        // explicitNulls = false omits null fields; removing the key restores the null default.311        val value = local[key]312        if (value == null) merged.remove(key) else merged[key] = value313    }314    return json.decodeFromJsonElement(DbSettings.serializer(), JsonObject(merged))315}316

Search chapters, reference and source filenames.