package eu.friedcutlet.yokan.services.sync import eu.friedcutlet.yokan.database.DbCategory import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbHistory import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbOutboxOp import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.database.SyncServerProvider import eu.friedcutlet.yokan.database.DbTrack import eu.friedcutlet.yokan.database.DbUpdate import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.library.removeTitleWithDependents import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.http.normalizeHubServer import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.database.sync.SyncClock import eu.friedcutlet.yokan.database.sync.SyncPaths import eu.friedcutlet.yokan.util.nowMillis import io.ktor.client.HttpClient import io.ktor.client.engine.HttpClientEngine import io.ktor.client.plugins.websocket.WebSockets import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.encodeToJsonElement import kotlinx.serialization.json.int import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive /** * Sync client for yokan-hub. One `POST /api/v1/sync` pushes this device's outbox and pulls the * delta since the stored cursor; `WS /api/v1/events` says when another device moved the head. * Design: `docs/SYNC_SERVER_PLAN.md`. * * Clocks never leave the hub: everything this device pushed is already inside the docs it gets * back, so the only local merge is "keep values for paths still pending in the outbox". */ class HubSyncService( private val database: YokanDatabase, private val http: HttpService, /** Engine for the live-events socket; owned by this service and closed in [close]. */ webSocketEngine: HttpClientEngine? = null, private val autoSync: Boolean = true, scope: CoroutineScope, private val operationMonitor: SyncOperationMonitor = SyncOperationMonitor(), private val leases: SyncAccountLeases = SyncAccountLeases.None, ) : SyncService { private val ownerJob = requireNotNull(scope.coroutineContext[Job]) { "Hub sync requires an owner job" } private val lifecycleJob = SupervisorJob(ownerJob) private val scope = CoroutineScope(scope.coroutineContext + lifecycleJob) private val retirementLock = Mutex() private val webSocketEngine = webSocketEngine?.let { eu.friedcutlet.yokan.services.http.ProfileHttpEngine(it, lifecycleJob) } override val operationState = operationMonitor.state private val json = SyncPaths.json private val liveClient: HttpClient? = this.webSocketEngine?.let { engine -> HttpClient(engine) { expectSuccess = false install(WebSockets) } } private val syncMutex = Mutex() private val hubLogin = HubLogin(database, http, leases) private val live = HubLiveEvents(this.scope, liveClient, leases, ::preference) { round(it, push = true, pull = true) } init { if (autoSync) this.scope.launch { database.snapshots().collect(live::onSnapshot) } } // ── SyncService ───────────────────────────────────────────────────────── override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult = hubLogin.login(syncId, server, email, password) override fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? = hubLogin.beginBrowserLogin(syncId, server) override suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult? = hubLogin.completeBrowserLogin(attempt, loadedUrl) override fun cancelBrowserLogin(attempt: BrowserLoginAttempt) = hubLogin.cancelBrowserLogin(attempt) override suspend fun logout(syncId: Long) { val pref = preference(syncId) val server = pref?.server?.let(::normalizeHubServer) // Removing the attempt first makes a racing browser completion's guard reject; never hold this lock across // the DB write, since saveLogin's guard takes it inside the DB lock. hubLogin.invalidate(syncId) upsertPreference(syncId) { it.copy(authToken = null, syncOn = false) } live.stopLive() leases.releaseQuietly(pref) // Revoking the session is best effort; an unreachable hub must not hold the local logout hostage. if (pref?.authToken != null && server != null) { scope.launch { catchingNonCancellation { http.request(HttpRequest(url = "$server/api/v1/logout", method = "POST", headers = authHeaders(pref))) } .onFailure { AppLogger.warn("[sync] hub logout request failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") } } } } override suspend fun sync(syncId: Long, settings: DbSettings): SyncResult = round(syncId, push = true, pull = true) override suspend fun pushChanges(syncId: Long): SyncResult = round(syncId, push = true, pull = false) override suspend fun pullChanges(syncId: Long): SyncResult = round(syncId, push = false, pull = true) override fun status(syncId: Long): SyncConnectionStatus { val pref = preference(syncId) return SyncConnectionStatus( loggedIn = !pref?.authToken.isNullOrBlank(), email = pref?.email, server = pref?.server, lastSyncMillis = pref?.lastSyncManga, ) } override fun close() { hubLogin.clear() scope.cancel() liveClient?.close() // Ktor never closes an engine passed to HttpClient(engine); without this OkHttp/Darwin threads leak. webSocketEngine?.close() } override suspend fun closeAndJoin() { retirementLock.withLock { withContext(kotlinx.coroutines.NonCancellable) { hubLogin.clear() lifecycleJob.cancelAndJoin() val clientJob = liveClient?.coroutineContext?.get(Job) clientJob?.cancel() webSocketEngine?.closeAndJoin() clientJob?.join() liveClient?.close() } } } // ── the round trip ────────────────────────────────────────────────────── /** * How a full copy of local state is stamped when it is pushed outside the outbox. * The outbox only holds edits made on this device since it started recording, so data that * predates it (first login, restored backups) has to be sent explicitly. */ private enum class Seed { /** Clock ≈ 0: fills gaps on the hub but never beats a value the hub already has. */ Conservative, /** Fresh clocks: local state wins everywhere ("Upload only"). */ Overwrite, ; fun clock(): Long = if (this == Overwrite) SyncClock.tick() else SEED_CLOCK } private suspend fun round(syncId: Long, push: Boolean, pull: Boolean): SyncResult { val stage = when { push && !pull -> SyncOperationStage.Uploading pull && !push -> SyncOperationStage.Downloading else -> SyncOperationStage.Syncing } val operationId = operationMonitor.begin(stage) return try { val result = performRound(syncId, push, pull) { operationMonitor.progress(operationId, it) } val summary = "[sync] hub ${stage.name.lowercase()}: ${result.uploadedChanges} up, ${result.downloadedChanges} down" if (result.errors.isEmpty()) AppLogger.info(summary) else AppLogger.warn("$summary; ${result.errors.joinToString("; ")}") operationMonitor.finish( operationId, if (result.errors.isEmpty()) SyncOperationOutcome.Succeeded else SyncOperationOutcome.Failed, ) result } catch (cancelled: CancellationException) { operationMonitor.finish(operationId, SyncOperationOutcome.Cancelled) throw cancelled } catch (error: Throwable) { AppLogger.error("[sync] hub ${stage.name.lowercase()} failed: ${error.message?.lineSequence()?.firstOrNull() ?: error::class.simpleName}") operationMonitor.finish(operationId, SyncOperationOutcome.Failed) throw error } } private suspend fun performRound( syncId: Long, push: Boolean, pull: Boolean, onProgress: (Float) -> Unit, ): SyncResult = syncMutex.withLock { var pref = preference(syncId) ?: return@withLock SyncResult(0, 0, false, listOf("No sync configuration.")) if (pref.serverProvider != SyncServerProvider.YokanHub) return@withLock SyncResult(0, 0, false, listOf("Yokan Hub is not the selected sync provider.")) val server = pref.server?.let(::normalizeHubServer) ?: return@withLock SyncResult(0, 0, false, listOf("No hub configured.")) if (pref.authToken.isNullOrBlank()) return@withLock SyncResult(0, 0, false, listOf("Not logged in.")) leases.claimFailure(pref)?.let { return@withLock SyncResult(0, 0, false, listOf(it)) } val operationToken = pref.authToken var uploaded = 0 var downloaded = 0 var lost = 0 var failedEntities = 0 val deferredDeletes = mutableListOf() var failure = "" fun done(vararg errors: String) = SyncResult( uploadedChanges = uploaded, downloadedChanges = downloaded, settingsSynced = pref.syncSettings && errors.isEmpty(), errors = errors.toList() + (if (lost > 0) listOf("$lost change(s) from another device took precedence.") else emptyList()) + (if (failedEntities > 0) listOf("$failedEntities incoming record(s) could not be applied.") else emptyList()) + deferredDeletes, ) /** One POST; null ends the round with [failure] set. A single 409 resets the cursor and retries. */ suspend fun exchange(build: (DbSyncPreference) -> SyncReq): SyncResp? { var resynced = false while (true) { val response = catchingNonCancellation { http.request( HttpRequest( url = "$server/api/v1/sync", method = "POST", headers = authHeaders(pref) + ("Content-Type" to "application/json"), body = json.encodeToString(SyncReq.serializer(), build(pref)), ), ) }.getOrElse { failure = "Could not reach the hub: ${it.message ?: "network error"}" return null } val activePreference = preference(syncId) if (activePreference?.serverProvider != SyncServerProvider.YokanHub || activePreference.server?.let(::normalizeHubServer) != server || activePreference.authToken != operationToken ) { failure = "Sync configuration changed during the operation." return null } when (response.statusCode) { 401 -> { upsertPreference(syncId) { it.copy(authToken = null) } live.stopLive() failure = "Session expired; log in to the hub again." return null } 503 -> { failure = "The hub is in maintenance mode; changes are kept locally." return null } 409 -> { if (resynced) { failure = "The hub asked for a second resync; giving up for now." return null } resynced = true val epoch = runCatching { json.parseToJsonElement(response.body).jsonObject["epoch"]?.jsonPrimitive?.int } .getOrNull() ?: 0 pref = database.resyncHub(syncId, epoch) continue } !in 200..299 -> { failure = "Hub returned HTTP ${response.statusCode}" return null } } val resp = runCatching { json.decodeFromString(SyncResp.serializer(), response.body) }.getOrElse { failure = "Unreadable hub response." return null } SyncClock.observe(resp.hlc) pref = upsertPreference(syncId) { it.copy(hubEpoch = resp.epoch, hubHlc = resp.hlc) } return resp } } val kinds = enabledKinds(pref) val seed = when { pref.hubRecoveryPending -> null !push -> null !pull -> Seed.Overwrite !pref.hubBootstrapComplete -> Seed.Conservative else -> null } if (seed != null) { val seeded = seedHub(kinds, seed, { pref.hubRecoveryPending }) { build -> exchange(build) } uploaded += seeded.uploaded lost += seeded.lost if (seeded.failed) return@withLock done(failure) if (seeded.completed && !pref.hubBootstrapComplete) { pref = upsertPreference(syncId) { it.copy(hubBootstrapComplete = true) } } } // ponytail: progress by seq range, not row count; seqs of rewritten rows leave gaps, so it can jump. val pullFrom = pref.hubHead while (true) { var ops = emptyList() val resp = exchange { // Re-read after a 409 resync: stale ops may have been // discarded before the retry is built. val eligible = eligibleOutbox(it) ops = if (push) { eligible.filter { op -> op.epoch == it.hubEpoch && (op.kind in kinds || op.kind in setOf(SyncPaths.KIND_HISTORY, SyncPaths.KIND_UPDATE) && op.path == SyncPaths.DELETED) }.take(MAX_OPS) } else { emptyList() } SyncReq( since = if (pull || it.hubRecoveryPending) it.hubHead else NO_DELTA, epoch = it.hubEpoch, generation = 1, hlc = SyncClock.tick(), ops = ops.map { op -> WireOp(op.kind, op.id, op.path, op.value?.let(json::parseToJsonElement) ?: JsonNull, op.hlc) }, ) } ?: return@withLock done(failure) if (ops.isNotEmpty()) { database.removeOutbox(ops) uploaded += ops.size lost += resp.lost } val shouldPull = pull || pref.hubRecoveryPending if (shouldPull) { val incoming = resp.ents.filter { it.k in kinds || it.del && it.k in setOf(SyncPaths.KIND_HISTORY, SyncPaths.KIND_UPDATE) } val (incomingFailed, deferred) = applyEntities(incoming, pref.hubEpoch) failedEntities += incomingFailed deferredDeletes += deferred downloaded += incoming.size val recoveryComplete = pref.hubRecoveryPending && !resp.more && incomingFailed == 0 pref = upsertPreference(syncId) { it.copy( hubHead = if (incomingFailed == 0) resp.head else it.hubHead, lastSyncManga = nowMillis(), hubRecoveryPending = if (recoveryComplete) false else it.hubRecoveryPending, hubBootstrapComplete = it.hubBootstrapComplete || recoveryComplete, ) } if (resp.more && resp.tip > pullFrom) { onProgress((resp.head - pullFrom).toFloat() / (resp.tip - pullFrom)) } } else { pref = upsertPreference(syncId) { it.copy( lastSyncManga = nowMillis(), hubBootstrapComplete = it.hubBootstrapComplete || (push && !it.hubBootstrapComplete && it.hubEpoch > 0), ) } } val morePush = push && ops.size == MAX_OPS if (!morePush && !(shouldPull && resp.more)) break } done() } private class SeedOutcome(val uploaded: Int, val lost: Int, val completed: Boolean, val failed: Boolean) /** * Pushes every local entity stamped by [seed]. NO_DELTA keeps the hub from paging its whole library back * on every chunk; the pull after it (or the next full sync) fetches the merged result from the stored cursor. * [exchange] returning null fails the seed; a recovery flagged by [recoveryPending] stops it unfinished. */ private suspend fun seedHub( kinds: Set, seed: Seed, recoveryPending: () -> Boolean, exchange: suspend ((DbSyncPreference) -> SyncReq) -> SyncResp?, ): SeedOutcome { var uploaded = 0 var lost = 0 for (chunk in localOps(kinds, seed)) { val resp = exchange { SyncReq( since = if (it.hubRecoveryPending) it.hubHead else NO_DELTA, epoch = it.hubEpoch, generation = 1, hlc = SyncClock.tick(), ops = if (it.hubRecoveryPending) emptyList() else chunk, ) } ?: return SeedOutcome(uploaded, lost, completed = false, failed = true) if (recoveryPending()) return SeedOutcome(uploaded, lost, completed = false, failed = false) uploaded += chunk.size lost += resp.lost } return SeedOutcome(uploaded, lost, completed = true, failed = false) } /** Drop pre-generation rows before selecting a batch; never relabel them as current. */ private fun eligibleOutbox(pref: DbSyncPreference): List { val current = database.outbox() if (!pref.hubBootstrapComplete) { return current.filter { it.epoch == 0 || it.epoch == pref.hubEpoch } } if (pref.hubEpoch == 0) return current val stale = current.filter { it.epoch < pref.hubEpoch } if (stale.isNotEmpty()) database.removeOutbox(stale) return database.outbox() } /** Every synced local entity as path ops, in request-sized chunks. */ private fun localOps(kinds: Set, seed: Seed): Sequence> = sequence { val chunk = ArrayList(MAX_OPS) for ((kind, id, doc) in SyncPaths.docs(database.snapshot(), kinds)) { for (change in SyncPaths.diff(kind, null, doc)) { chunk += WireOp(kind, id, change.path, change.value ?: JsonNull, seed.clock()) if (chunk.size == MAX_OPS) { yield(chunk.toList()) chunk.clear() } } } if (chunk.isNotEmpty()) yield(chunk.toList()) } /** Apply hub docs locally. Returns the failed count and actionable deferred-delete errors. */ private fun applyEntities(ents: List, epoch: Int): Pair> { if (ents.isEmpty()) return 0 to emptyList() var failed = 0 val deferred = mutableListOf() database.applyRemote { database.batch { // Re-read within the transaction: unsent lower-sequence edits matter too. val pending = database.outbox().filter { it.epoch == epoch }.groupBy { it.kind to it.id } for (e in ents) { val result = runCatching { if (e.del) { if (e.k == SyncPaths.KIND_MANGA) { val chapterIds = database.chapters(e.id).mapTo(HashSet()) { it.id } if (database.downloads().any { it.chapterId?.let(chapterIds::contains) == true && it.isStartDownload == true && it.isDownload != true }) { error("Title ${e.id} has an active chapter download; finish or cancel it before syncing this deletion.") } } removeEntity(e.k, e.id) } else { val ops = pending[e.k to e.id].orEmpty() if (ops.none { it.path == SyncPaths.DELETED && it.value?.let(json::parseToJsonElement) == kotlinx.serialization.json.JsonPrimitive(true) }) { e.doc?.let { applyEntity(e.k, e.id, SyncPaths.overlay(it, ops)) } } } } result.exceptionOrNull()?.let { exception -> failed++ exception.message?.takeIf { it.startsWith("Title ") }?.let(deferred::add) } } } } return failed to deferred } private fun removeEntity(kind: Int, id: Long) { when (kind) { SyncPaths.KIND_CATEGORY -> database.removeCategory(id, recordChange = false) SyncPaths.KIND_MANGA -> removeTitleWithDependents(database, id, recordChange = false) SyncPaths.KIND_CHAPTER -> database.removeChapter(id, recordChange = false) SyncPaths.KIND_TRACK -> database.removeTrack(id, recordChange = false) SyncPaths.KIND_HISTORY -> database.removeHistory(id, recordChange = false) SyncPaths.KIND_UPDATE -> database.removeUpdate(id, recordChange = false) } } private fun applyEntity(kind: Int, id: Long, doc: JsonObject) { when (kind) { SyncPaths.KIND_MANGA -> database.upsertManga(decode(kind, id, doc, DbManga.serializer()) { database.manga(id) }) SyncPaths.KIND_CHAPTER -> database.upsertChapter(decode(kind, id, doc, DbChapter.serializer()) { database.chapter(id) }) SyncPaths.KIND_CATEGORY -> database.upsertCategory(decode(kind, id, doc, DbCategory.serializer()) { database.categories().firstOrNull { it.id == id } }) SyncPaths.KIND_TRACK -> database.upsertTrack(decode(kind, id, doc, DbTrack.serializer()) { database.tracks().firstOrNull { it.id == id } }) SyncPaths.KIND_HISTORY -> database.upsertHistory(decode(kind, id, doc, DbHistory.serializer()) { database.histories().firstOrNull { it.id == id } }) SyncPaths.KIND_UPDATE -> database.upsertUpdate(decode(kind, id, doc, DbUpdate.serializer()) { database.updates().firstOrNull { it.id == id } }) SyncPaths.KIND_SETTINGS -> { val current = database.settings() database.updateSettings(decode(kind, id, doc, DbSettings.serializer()) { current }.copy(id = current.id)) } } } /** * Only excluded (device-local) fields survive from the local row, so it is looked up only for * kinds that have some; a full-table scan per pulled row made large pulls quadratic. */ private fun decode(kind: Int, id: Long, doc: JsonObject, serializer: KSerializer, local: () -> T?): T { val localObj = if (SyncPaths.excluded(kind).any { it != "id" }) { local()?.let { json.encodeToJsonElement(serializer, it).jsonObject } } else { null } return json.decodeFromJsonElement(serializer, SyncPaths.applyIncoming(kind, localObj, doc, id)) } // ── helpers ───────────────────────────────────────────────────────────── private fun preference(syncId: Long): DbSyncPreference? = database.syncPreferences().firstOrNull { it.syncId == syncId } private fun upsertPreference(syncId: Long, transform: (DbSyncPreference) -> DbSyncPreference): DbSyncPreference { val current = preference(syncId) ?: DbSyncPreference(syncId = syncId) return database.upsertSyncPreference(transform(current.copy(syncId = current.syncId ?: syncId))) } private fun enabledKinds(pref: DbSyncPreference): Set = buildSet { add(SyncPaths.KIND_CATEGORY) add(SyncPaths.KIND_MANGA) add(SyncPaths.KIND_CHAPTER) add(SyncPaths.KIND_TRACK) if (pref.syncHistories) add(SyncPaths.KIND_HISTORY) if (pref.syncUpdates) add(SyncPaths.KIND_UPDATE) if (pref.syncSettings) add(SyncPaths.KIND_SETTINGS) } private fun authHeaders(pref: DbSyncPreference): Map = mapOf("Authorization" to "Bearer ${pref.authToken}", "X-Device" to (pref.deviceId ?: "unknown")) @Serializable private data class WireOp(val k: Int, val id: Long, val p: String, val v: JsonElement = JsonNull, val t: Long) @Serializable private data class SyncReq( val since: Long, val epoch: Int, val generation: Int, val hlc: Long, val ops: List, ) @Serializable private data class WireEnt(val k: Int, val id: Long, val doc: JsonObject? = null, val del: Boolean = false) @Serializable private data class SyncResp( val epoch: Int, val head: Long, val hlc: Long, val more: Boolean = false, val ents: List = emptyList(), val lost: Int = 0, val applied: Int = 0, /** Hub's newest seq; with [head] it tells how far a multi-page pull got. 0 from older hubs. */ val tip: Long = 0, ) companion object { const val PUSH_DEBOUNCE_MS = 3_000L /** Hub-side limit per request (`MAX_OPS` in `routes/sync.rs`). */ const val MAX_OPS = 10_000 /** `since` beyond any seq: the hub validates the epoch but returns no delta. */ const val NO_DELTA = Long.MAX_VALUE /** Smallest clock the hub accepts as a real write; loses to anything already stored. */ val SEED_CLOCK = SyncClock.pack(1, 0) /** Sync protocol this client speaks; checked against the hub's `GET /api/version` at login. */ const val PROTOCOL_VERSION = "1" } }