Yokan / rebuild
Course 1 8624561

HubSyncService.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubSyncService.kt

implementation563 lines
1package eu.friedcutlet.yokan.services.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.DbSettings9import eu.friedcutlet.yokan.database.DbSyncPreference10import eu.friedcutlet.yokan.database.SyncServerProvider11import eu.friedcutlet.yokan.database.DbTrack12import eu.friedcutlet.yokan.database.DbUpdate13import eu.friedcutlet.yokan.database.YokanDatabase14import eu.friedcutlet.yokan.services.catchingNonCancellation15import eu.friedcutlet.yokan.services.library.removeTitleWithDependents16import eu.friedcutlet.yokan.services.http.HttpRequest17import eu.friedcutlet.yokan.services.http.HttpService18import eu.friedcutlet.yokan.services.http.normalizeHubServer19import eu.friedcutlet.yokan.services.logging.AppLogger20import eu.friedcutlet.yokan.database.sync.SyncClock21import eu.friedcutlet.yokan.database.sync.SyncPaths22import eu.friedcutlet.yokan.util.nowMillis23import io.ktor.client.HttpClient24import io.ktor.client.engine.HttpClientEngine25import io.ktor.client.plugins.websocket.WebSockets26import kotlinx.coroutines.CancellationException27import kotlinx.coroutines.CoroutineScope28import kotlinx.coroutines.Job29import kotlinx.coroutines.SupervisorJob30import kotlinx.coroutines.cancel31import kotlinx.coroutines.cancelAndJoin32import kotlinx.coroutines.launch33import kotlinx.coroutines.withContext34import kotlinx.coroutines.sync.Mutex35import kotlinx.coroutines.sync.withLock36import kotlinx.serialization.KSerializer37import kotlinx.serialization.Serializable38import kotlinx.serialization.json.JsonElement39import kotlinx.serialization.json.JsonNull40import kotlinx.serialization.json.JsonObject41import kotlinx.serialization.json.encodeToJsonElement42import kotlinx.serialization.json.int43import kotlinx.serialization.json.jsonObject44import kotlinx.serialization.json.jsonPrimitive4546/**47 * Sync client for yokan-hub. One `POST /api/v1/sync` pushes this device's outbox and pulls the48 * delta since the stored cursor; `WS /api/v1/events` says when another device moved the head.49 * Design: `docs/SYNC_SERVER_PLAN.md`.50 *51 * Clocks never leave the hub: everything this device pushed is already inside the docs it gets52 * back, so the only local merge is "keep values for paths still pending in the outbox".53 */54class HubSyncService(55    private val database: YokanDatabase,56    private val http: HttpService,57    /** Engine for the live-events socket; owned by this service and closed in [close]. */58    webSocketEngine: HttpClientEngine? = null,59    private val autoSync: Boolean = true,60    scope: CoroutineScope,61    private val operationMonitor: SyncOperationMonitor = SyncOperationMonitor(),62    private val leases: SyncAccountLeases = SyncAccountLeases.None,63) : SyncService {64    private val ownerJob = requireNotNull(scope.coroutineContext[Job]) { "Hub sync requires an owner job" }65    private val lifecycleJob = SupervisorJob(ownerJob)66    private val scope = CoroutineScope(scope.coroutineContext + lifecycleJob)67    private val retirementLock = Mutex()68    private val webSocketEngine = webSocketEngine?.let { eu.friedcutlet.yokan.services.http.ProfileHttpEngine(it, lifecycleJob) }69    override val operationState = operationMonitor.state70    private val json = SyncPaths.json71    private val liveClient: HttpClient? = this.webSocketEngine?.let { engine ->72        HttpClient(engine) {73            expectSuccess = false74            install(WebSockets)75        }76    }77    private val syncMutex = Mutex()78    private val hubLogin = HubLogin(database, http, leases)79    private val live = HubLiveEvents(this.scope, liveClient, leases, ::preference) { round(it, push = true, pull = true) }8081    init {82        if (autoSync) this.scope.launch { database.snapshots().collect(live::onSnapshot) }83    }8485    // ── SyncService ─────────────────────────────────────────────────────────8687    override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult =88        hubLogin.login(syncId, server, email, password)8990    override fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? = hubLogin.beginBrowserLogin(syncId, server)9192    override suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult? =93        hubLogin.completeBrowserLogin(attempt, loadedUrl)9495    override fun cancelBrowserLogin(attempt: BrowserLoginAttempt) = hubLogin.cancelBrowserLogin(attempt)9697    override suspend fun logout(syncId: Long) {98        val pref = preference(syncId)99        val server = pref?.server?.let(::normalizeHubServer)100        // Removing the attempt first makes a racing browser completion's guard reject; never hold this lock across101        // the DB write, since saveLogin's guard takes it inside the DB lock.102        hubLogin.invalidate(syncId)103        upsertPreference(syncId) { it.copy(authToken = null, syncOn = false) }104        live.stopLive()105        leases.releaseQuietly(pref)106        // Revoking the session is best effort; an unreachable hub must not hold the local logout hostage.107        if (pref?.authToken != null && server != null) {108            scope.launch {109                catchingNonCancellation { http.request(HttpRequest(url = "$server/api/v1/logout", method = "POST", headers = authHeaders(pref))) }110                    .onFailure { AppLogger.warn("[sync] hub logout request failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }111            }112        }113    }114115    override suspend fun sync(syncId: Long, settings: DbSettings): SyncResult = round(syncId, push = true, pull = true)116117    override suspend fun pushChanges(syncId: Long): SyncResult = round(syncId, push = true, pull = false)118119    override suspend fun pullChanges(syncId: Long): SyncResult = round(syncId, push = false, pull = true)120121    override fun status(syncId: Long): SyncConnectionStatus {122        val pref = preference(syncId)123        return SyncConnectionStatus(124            loggedIn = !pref?.authToken.isNullOrBlank(),125            email = pref?.email,126            server = pref?.server,127            lastSyncMillis = pref?.lastSyncManga,128        )129    }130131    override fun close() {132        hubLogin.clear()133        scope.cancel()134        liveClient?.close()135        // Ktor never closes an engine passed to HttpClient(engine); without this OkHttp/Darwin threads leak.136        webSocketEngine?.close()137    }138139    override suspend fun closeAndJoin() {140        retirementLock.withLock {141            withContext(kotlinx.coroutines.NonCancellable) {142                hubLogin.clear()143                lifecycleJob.cancelAndJoin()144                val clientJob = liveClient?.coroutineContext?.get(Job)145                clientJob?.cancel()146                webSocketEngine?.closeAndJoin()147                clientJob?.join()148                liveClient?.close()149            }150        }151    }152153    // ── the round trip ──────────────────────────────────────────────────────154155    /**156     * How a full copy of local state is stamped when it is pushed outside the outbox.157     * The outbox only holds edits made on this device since it started recording, so data that158     * predates it (first login, restored backups) has to be sent explicitly.159     */160    private enum class Seed {161        /** Clock ≈ 0: fills gaps on the hub but never beats a value the hub already has. */162        Conservative,163        /** Fresh clocks: local state wins everywhere ("Upload only"). */164        Overwrite,165        ;166167        fun clock(): Long = if (this == Overwrite) SyncClock.tick() else SEED_CLOCK168    }169170    private suspend fun round(syncId: Long, push: Boolean, pull: Boolean): SyncResult {171        val stage = when {172            push && !pull -> SyncOperationStage.Uploading173            pull && !push -> SyncOperationStage.Downloading174            else -> SyncOperationStage.Syncing175        }176        val operationId = operationMonitor.begin(stage)177        return try {178            val result = performRound(syncId, push, pull) { operationMonitor.progress(operationId, it) }179            val summary = "[sync] hub ${stage.name.lowercase()}: ${result.uploadedChanges} up, ${result.downloadedChanges} down"180            if (result.errors.isEmpty()) AppLogger.info(summary) else AppLogger.warn("$summary; ${result.errors.joinToString("; ")}")181            operationMonitor.finish(182                operationId,183                if (result.errors.isEmpty()) SyncOperationOutcome.Succeeded else SyncOperationOutcome.Failed,184            )185            result186        } catch (cancelled: CancellationException) {187            operationMonitor.finish(operationId, SyncOperationOutcome.Cancelled)188            throw cancelled189        } catch (error: Throwable) {190            AppLogger.error("[sync] hub ${stage.name.lowercase()} failed: ${error.message?.lineSequence()?.firstOrNull() ?: error::class.simpleName}")191            operationMonitor.finish(operationId, SyncOperationOutcome.Failed)192            throw error193        }194    }195196    private suspend fun performRound(197        syncId: Long,198        push: Boolean,199        pull: Boolean,200        onProgress: (Float) -> Unit,201    ): SyncResult = syncMutex.withLock {202        var pref = preference(syncId) ?: return@withLock SyncResult(0, 0, false, listOf("No sync configuration."))203        if (pref.serverProvider != SyncServerProvider.YokanHub) return@withLock SyncResult(0, 0, false, listOf("Yokan Hub is not the selected sync provider."))204        val server = pref.server?.let(::normalizeHubServer) ?: return@withLock SyncResult(0, 0, false, listOf("No hub configured."))205        if (pref.authToken.isNullOrBlank()) return@withLock SyncResult(0, 0, false, listOf("Not logged in."))206        leases.claimFailure(pref)?.let { return@withLock SyncResult(0, 0, false, listOf(it)) }207        val operationToken = pref.authToken208209        var uploaded = 0210        var downloaded = 0211        var lost = 0212        var failedEntities = 0213        val deferredDeletes = mutableListOf<String>()214        var failure = ""215        fun done(vararg errors: String) = SyncResult(216            uploadedChanges = uploaded,217            downloadedChanges = downloaded,218            settingsSynced = pref.syncSettings && errors.isEmpty(),219            errors = errors.toList() +220                (if (lost > 0) listOf("$lost change(s) from another device took precedence.") else emptyList()) +221                (if (failedEntities > 0) listOf("$failedEntities incoming record(s) could not be applied.") else emptyList()) + deferredDeletes,222        )223224        /** One POST; null ends the round with [failure] set. A single 409 resets the cursor and retries. */225        suspend fun exchange(build: (DbSyncPreference) -> SyncReq): SyncResp? {226            var resynced = false227            while (true) {228                val response = catchingNonCancellation {229                    http.request(230                        HttpRequest(231                            url = "$server/api/v1/sync",232                            method = "POST",233                            headers = authHeaders(pref) + ("Content-Type" to "application/json"),234                            body = json.encodeToString(SyncReq.serializer(), build(pref)),235                        ),236                    )237                }.getOrElse {238                    failure = "Could not reach the hub: ${it.message ?: "network error"}"239                    return null240                }241                val activePreference = preference(syncId)242                if (activePreference?.serverProvider != SyncServerProvider.YokanHub ||243                    activePreference.server?.let(::normalizeHubServer) != server || activePreference.authToken != operationToken244                ) {245                    failure = "Sync configuration changed during the operation."246                    return null247                }248                when (response.statusCode) {249                    401 -> {250                        upsertPreference(syncId) { it.copy(authToken = null) }251                        live.stopLive()252                        failure = "Session expired; log in to the hub again."253                        return null254                    }255                    503 -> {256                        failure = "The hub is in maintenance mode; changes are kept locally."257                        return null258                    }259                    409 -> {260                        if (resynced) {261                            failure = "The hub asked for a second resync; giving up for now."262                            return null263                        }264                        resynced = true265                        val epoch = runCatching { json.parseToJsonElement(response.body).jsonObject["epoch"]?.jsonPrimitive?.int }266                            .getOrNull() ?: 0267                        pref = database.resyncHub(syncId, epoch)268                        continue269                    }270                    !in 200..299 -> {271                        failure = "Hub returned HTTP ${response.statusCode}"272                        return null273                    }274                }275                val resp = runCatching { json.decodeFromString(SyncResp.serializer(), response.body) }.getOrElse {276                    failure = "Unreadable hub response."277                    return null278                }279                SyncClock.observe(resp.hlc)280                pref = upsertPreference(syncId) { it.copy(hubEpoch = resp.epoch, hubHlc = resp.hlc) }281                return resp282            }283        }284285        val kinds = enabledKinds(pref)286        val seed = when {287            pref.hubRecoveryPending -> null288            !push -> null289            !pull -> Seed.Overwrite290            !pref.hubBootstrapComplete -> Seed.Conservative291            else -> null292        }293        if (seed != null) {294            val seeded = seedHub(kinds, seed, { pref.hubRecoveryPending }) { build -> exchange(build) }295            uploaded += seeded.uploaded296            lost += seeded.lost297            if (seeded.failed) return@withLock done(failure)298            if (seeded.completed && !pref.hubBootstrapComplete) {299                pref = upsertPreference(syncId) { it.copy(hubBootstrapComplete = true) }300            }301        }302303        // ponytail: progress by seq range, not row count; seqs of rewritten rows leave gaps, so it can jump.304        val pullFrom = pref.hubHead305        while (true) {306            var ops = emptyList<DbOutboxOp>()307            val resp = exchange {308                // Re-read after a 409 resync: stale ops may have been309                // discarded before the retry is built.310                val eligible = eligibleOutbox(it)311                ops = if (push) {312                    eligible.filter { op ->313                        op.epoch == it.hubEpoch &&314                            (op.kind in kinds || op.kind in setOf(SyncPaths.KIND_HISTORY, SyncPaths.KIND_UPDATE) && op.path == SyncPaths.DELETED)315                    }.take(MAX_OPS)316                } else {317                    emptyList()318                }319                SyncReq(320                    since = if (pull || it.hubRecoveryPending) it.hubHead else NO_DELTA,321                    epoch = it.hubEpoch,322                    generation = 1,323                    hlc = SyncClock.tick(),324                    ops = ops.map { op -> WireOp(op.kind, op.id, op.path, op.value?.let(json::parseToJsonElement) ?: JsonNull, op.hlc) },325                )326            } ?: return@withLock done(failure)327328            if (ops.isNotEmpty()) {329                database.removeOutbox(ops)330                uploaded += ops.size331                lost += resp.lost332            }333            val shouldPull = pull || pref.hubRecoveryPending334            if (shouldPull) {335                val incoming = resp.ents.filter { it.k in kinds || it.del && it.k in setOf(SyncPaths.KIND_HISTORY, SyncPaths.KIND_UPDATE) }336                val (incomingFailed, deferred) = applyEntities(incoming, pref.hubEpoch)337                failedEntities += incomingFailed338                deferredDeletes += deferred339                downloaded += incoming.size340                val recoveryComplete = pref.hubRecoveryPending && !resp.more && incomingFailed == 0341                pref = upsertPreference(syncId) {342                    it.copy(343                        hubHead = if (incomingFailed == 0) resp.head else it.hubHead,344                        lastSyncManga = nowMillis(),345                        hubRecoveryPending = if (recoveryComplete) false else it.hubRecoveryPending,346                        hubBootstrapComplete = it.hubBootstrapComplete || recoveryComplete,347                    )348                }349                if (resp.more && resp.tip > pullFrom) {350                    onProgress((resp.head - pullFrom).toFloat() / (resp.tip - pullFrom))351                }352            } else {353                pref = upsertPreference(syncId) {354                    it.copy(355                        lastSyncManga = nowMillis(),356                        hubBootstrapComplete = it.hubBootstrapComplete ||357                            (push && !it.hubBootstrapComplete && it.hubEpoch > 0),358                    )359                }360            }361            val morePush = push && ops.size == MAX_OPS362            if (!morePush && !(shouldPull && resp.more)) break363        }364        done()365    }366367    private class SeedOutcome(val uploaded: Int, val lost: Int, val completed: Boolean, val failed: Boolean)368369    /**370     * Pushes every local entity stamped by [seed]. NO_DELTA keeps the hub from paging its whole library back371     * on every chunk; the pull after it (or the next full sync) fetches the merged result from the stored cursor.372     * [exchange] returning null fails the seed; a recovery flagged by [recoveryPending] stops it unfinished.373     */374    private suspend fun seedHub(375        kinds: Set<Int>,376        seed: Seed,377        recoveryPending: () -> Boolean,378        exchange: suspend ((DbSyncPreference) -> SyncReq) -> SyncResp?,379    ): SeedOutcome {380        var uploaded = 0381        var lost = 0382        for (chunk in localOps(kinds, seed)) {383            val resp = exchange {384                SyncReq(385                    since = if (it.hubRecoveryPending) it.hubHead else NO_DELTA,386                    epoch = it.hubEpoch,387                    generation = 1,388                    hlc = SyncClock.tick(),389                    ops = if (it.hubRecoveryPending) emptyList() else chunk,390                )391            } ?: return SeedOutcome(uploaded, lost, completed = false, failed = true)392            if (recoveryPending()) return SeedOutcome(uploaded, lost, completed = false, failed = false)393            uploaded += chunk.size394            lost += resp.lost395        }396        return SeedOutcome(uploaded, lost, completed = true, failed = false)397    }398399    /** Drop pre-generation rows before selecting a batch; never relabel them as current. */400    private fun eligibleOutbox(pref: DbSyncPreference): List<DbOutboxOp> {401        val current = database.outbox()402        if (!pref.hubBootstrapComplete) {403            return current.filter { it.epoch == 0 || it.epoch == pref.hubEpoch }404        }405        if (pref.hubEpoch == 0) return current406        val stale = current.filter { it.epoch < pref.hubEpoch }407        if (stale.isNotEmpty()) database.removeOutbox(stale)408        return database.outbox()409    }410411    /** Every synced local entity as path ops, in request-sized chunks. */412    private fun localOps(kinds: Set<Int>, seed: Seed): Sequence<List<WireOp>> = sequence {413        val chunk = ArrayList<WireOp>(MAX_OPS)414        for ((kind, id, doc) in SyncPaths.docs(database.snapshot(), kinds)) {415            for (change in SyncPaths.diff(kind, null, doc)) {416                chunk += WireOp(kind, id, change.path, change.value ?: JsonNull, seed.clock())417                if (chunk.size == MAX_OPS) {418                    yield(chunk.toList())419                    chunk.clear()420                }421            }422        }423        if (chunk.isNotEmpty()) yield(chunk.toList())424    }425426    /** Apply hub docs locally. Returns the failed count and actionable deferred-delete errors. */427    private fun applyEntities(ents: List<WireEnt>, epoch: Int): Pair<Int, List<String>> {428        if (ents.isEmpty()) return 0 to emptyList()429        var failed = 0430        val deferred = mutableListOf<String>()431        database.applyRemote {432            database.batch {433                // Re-read within the transaction: unsent lower-sequence edits matter too.434                val pending = database.outbox().filter { it.epoch == epoch }.groupBy { it.kind to it.id }435                for (e in ents) {436                    val result = runCatching {437                        if (e.del) {438                            if (e.k == SyncPaths.KIND_MANGA) {439                                val chapterIds = database.chapters(e.id).mapTo(HashSet()) { it.id }440                                if (database.downloads().any { it.chapterId?.let(chapterIds::contains) == true && it.isStartDownload == true && it.isDownload != true }) {441                                    error("Title ${e.id} has an active chapter download; finish or cancel it before syncing this deletion.")442                                }443                            }444                            removeEntity(e.k, e.id)445                        } else {446                            val ops = pending[e.k to e.id].orEmpty()447                            if (ops.none { it.path == SyncPaths.DELETED && it.value?.let(json::parseToJsonElement) == kotlinx.serialization.json.JsonPrimitive(true) }) {448                                e.doc?.let { applyEntity(e.k, e.id, SyncPaths.overlay(it, ops)) }449                            }450                        }451                    }452                    result.exceptionOrNull()?.let { exception ->453                        failed++454                        exception.message?.takeIf { it.startsWith("Title ") }?.let(deferred::add)455                    }456                }457            }458        }459        return failed to deferred460    }461462    private fun removeEntity(kind: Int, id: Long) {463        when (kind) {464            SyncPaths.KIND_CATEGORY -> database.removeCategory(id, recordChange = false)465            SyncPaths.KIND_MANGA -> removeTitleWithDependents(database, id, recordChange = false)466            SyncPaths.KIND_CHAPTER -> database.removeChapter(id, recordChange = false)467            SyncPaths.KIND_TRACK -> database.removeTrack(id, recordChange = false)468            SyncPaths.KIND_HISTORY -> database.removeHistory(id, recordChange = false)469            SyncPaths.KIND_UPDATE -> database.removeUpdate(id, recordChange = false)470        }471    }472473    private fun applyEntity(kind: Int, id: Long, doc: JsonObject) {474        when (kind) {475            SyncPaths.KIND_MANGA -> database.upsertManga(decode(kind, id, doc, DbManga.serializer()) { database.manga(id) })476            SyncPaths.KIND_CHAPTER -> database.upsertChapter(decode(kind, id, doc, DbChapter.serializer()) { database.chapter(id) })477            SyncPaths.KIND_CATEGORY -> database.upsertCategory(decode(kind, id, doc, DbCategory.serializer()) { database.categories().firstOrNull { it.id == id } })478            SyncPaths.KIND_TRACK -> database.upsertTrack(decode(kind, id, doc, DbTrack.serializer()) { database.tracks().firstOrNull { it.id == id } })479            SyncPaths.KIND_HISTORY -> database.upsertHistory(decode(kind, id, doc, DbHistory.serializer()) { database.histories().firstOrNull { it.id == id } })480            SyncPaths.KIND_UPDATE -> database.upsertUpdate(decode(kind, id, doc, DbUpdate.serializer()) { database.updates().firstOrNull { it.id == id } })481            SyncPaths.KIND_SETTINGS -> {482                val current = database.settings()483                database.updateSettings(decode(kind, id, doc, DbSettings.serializer()) { current }.copy(id = current.id))484            }485        }486    }487488    /**489     * Only excluded (device-local) fields survive from the local row, so it is looked up only for490     * kinds that have some; a full-table scan per pulled row made large pulls quadratic.491     */492    private fun <T> decode(kind: Int, id: Long, doc: JsonObject, serializer: KSerializer<T>, local: () -> T?): T {493        val localObj = if (SyncPaths.excluded(kind).any { it != "id" }) {494            local()?.let { json.encodeToJsonElement(serializer, it).jsonObject }495        } else {496            null497        }498        return json.decodeFromJsonElement(serializer, SyncPaths.applyIncoming(kind, localObj, doc, id))499    }500501    // ── helpers ─────────────────────────────────────────────────────────────502503    private fun preference(syncId: Long): DbSyncPreference? =504        database.syncPreferences().firstOrNull { it.syncId == syncId }505506    private fun upsertPreference(syncId: Long, transform: (DbSyncPreference) -> DbSyncPreference): DbSyncPreference {507        val current = preference(syncId) ?: DbSyncPreference(syncId = syncId)508        return database.upsertSyncPreference(transform(current.copy(syncId = current.syncId ?: syncId)))509    }510511    private fun enabledKinds(pref: DbSyncPreference): Set<Int> = buildSet {512        add(SyncPaths.KIND_CATEGORY)513        add(SyncPaths.KIND_MANGA)514        add(SyncPaths.KIND_CHAPTER)515        add(SyncPaths.KIND_TRACK)516        if (pref.syncHistories) add(SyncPaths.KIND_HISTORY)517        if (pref.syncUpdates) add(SyncPaths.KIND_UPDATE)518        if (pref.syncSettings) add(SyncPaths.KIND_SETTINGS)519    }520521    private fun authHeaders(pref: DbSyncPreference): Map<String, String> =522        mapOf("Authorization" to "Bearer ${pref.authToken}", "X-Device" to (pref.deviceId ?: "unknown"))523524    @Serializable525    private data class WireOp(val k: Int, val id: Long, val p: String, val v: JsonElement = JsonNull, val t: Long)526527    @Serializable528    private data class SyncReq(529        val since: Long,530        val epoch: Int,531        val generation: Int,532        val hlc: Long,533        val ops: List<WireOp>,534    )535536    @Serializable537    private data class WireEnt(val k: Int, val id: Long, val doc: JsonObject? = null, val del: Boolean = false)538539    @Serializable540    private data class SyncResp(541        val epoch: Int,542        val head: Long,543        val hlc: Long,544        val more: Boolean = false,545        val ents: List<WireEnt> = emptyList(),546        val lost: Int = 0,547        val applied: Int = 0,548        /** Hub's newest seq; with [head] it tells how far a multi-page pull got. 0 from older hubs. */549        val tip: Long = 0,550    )551552    companion object {553        const val PUSH_DEBOUNCE_MS = 3_000L554        /** Hub-side limit per request (`MAX_OPS` in `routes/sync.rs`). */555        const val MAX_OPS = 10_000556        /** `since` beyond any seq: the hub validates the epoch but returns no delta. */557        const val NO_DELTA = Long.MAX_VALUE558        /** Smallest clock the hub accepts as a real write; loses to anything already stored. */559        val SEED_CLOCK = SyncClock.pack(1, 0)560        /** Sync protocol this client speaks; checked against the hub's `GET /api/version` at login. */561        const val PROTOCOL_VERSION = "1"562    }563}564

Search chapters, reference and source filenames.