HubLiveEvents.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/HubLiveEvents.kt
1package eu.friedcutlet.yokan.services.sync23import eu.friedcutlet.yokan.database.DbSyncPreference4import eu.friedcutlet.yokan.database.SyncServerProvider5import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot6import eu.friedcutlet.yokan.database.sync.SyncPaths7import eu.friedcutlet.yokan.services.http.hubWebSocketBase8import eu.friedcutlet.yokan.services.http.normalizeHubServer9import eu.friedcutlet.yokan.services.logging.AppLogger10import io.ktor.client.HttpClient11import io.ktor.client.plugins.websocket.webSocket12import io.ktor.client.request.header13import io.ktor.http.HttpHeaders14import io.ktor.websocket.Frame15import io.ktor.websocket.readText16import kotlinx.coroutines.CancellationException17import kotlinx.coroutines.CoroutineScope18import kotlinx.coroutines.Job19import kotlinx.coroutines.delay20import kotlinx.coroutines.isActive21import kotlinx.coroutines.launch22import kotlinx.coroutines.sync.Mutex23import kotlinx.coroutines.sync.withLock24import kotlinx.serialization.json.jsonObject25import kotlinx.serialization.json.jsonPrimitive26import kotlinx.serialization.json.long2728/** `WS /api/v1/events` hints plus the debounced push after local edits, for [HubSyncService]. */29internal class HubLiveEvents(30 private val scope: CoroutineScope,31 private val liveClient: HttpClient?,32 private val leases: SyncAccountLeases,33 private val preference: (Long) -> DbSyncPreference?,34 private val round: suspend (syncId: Long) -> SyncResult,35) {36 private val json = SyncPaths.json37 private val stateMutex = Mutex()38 private var liveKey: LiveKey? = null39 private var liveJob: Job? = null40 private var pushJob: Job? = null41 private var lastOutboxSeq = -1L4243 private data class LiveKey(val syncId: Long, val server: String, val token: String, val device: String)4445 suspend fun onSnapshot(snapshot: YokanDatabaseSnapshot) {46 val pref = snapshot.syncPreferences.firstOrNull()47 val key = pref48 ?.takeIf { it.syncOn }49 ?.takeIf { it.serverProvider == SyncServerProvider.YokanHub }50 ?.let { p ->51 val token = p.authToken?.takeIf { it.isNotBlank() } ?: return@let null52 normalizeHubServer(p.server)?.let { LiveKey(p.syncId ?: 1L, it, token, p.deviceId ?: "unknown") }53 }54 val outboxSeq = snapshot.outbox.maxOfOrNull { it.seq } ?: 0L55 stateMutex.withLock {56 val keyChanged = key != liveKey57 if (keyChanged) {58 liveJob?.cancel()59 pushJob?.cancel()60 liveKey = key61 liveJob = if (key != null && liveClient != null) scope.launch { runLive(key) } else null62 }63 if (key != null && (outboxSeq > lastOutboxSeq || keyChanged && outboxSeq > 0)) schedulePushLocked(key.syncId)64 lastOutboxSeq = outboxSeq65 }66 }6768 suspend fun stopLive() = stateMutex.withLock {69 liveJob?.cancel()70 liveJob = null71 liveKey = null72 }7374 private fun schedulePushLocked(syncId: Long) {75 pushJob?.cancel()76 pushJob = scope.launch {77 delay(HubSyncService.PUSH_DEBOUNCE_MS)78 round(syncId)79 }80 }8182 private suspend fun runLive(key: LiveKey) {83 val client = liveClient ?: return84 leases.claimFailure(preference(key.syncId))?.let { AppLogger.warn("[sync] hub live events not started: $it"); return }85 var backoff = 1_000L86 while (scope.isActive && stateMutex.withLock { liveKey == key }) {87 try {88 client.webSocket(89 urlString = hubWebSocketBase(key.server) + "/api/v1/events",90 request = {91 header(HttpHeaders.Authorization, "Bearer ${key.token}")92 header("X-Device", key.device)93 },94 ) {95 backoff = 1_000L96 round(key.syncId)97 for (frame in incoming) {98 val text = (frame as? Frame.Text)?.readText() ?: continue99 val head = runCatching { json.parseToJsonElement(text).jsonObject["head"]?.jsonPrimitive?.long }.getOrNull() ?: continue100 if (head > (preference(key.syncId)?.hubHead ?: 0L)) round(key.syncId)101 }102 }103 } catch (cancelled: CancellationException) {104 throw cancelled105 } catch (error: Throwable) {106 // The REST round trip stays authoritative; a socket failure only delays hints.107 // Logged once per outage: the backoff only stays at its base until the first retry.108 if (backoff == 1_000L) {109 AppLogger.warn("[sync] hub live events disconnected: ${error.message?.lineSequence()?.firstOrNull() ?: error::class.simpleName}")110 }111 }112 if (!scope.isActive) break113 delay(backoff)114 backoff = (backoff * 2).coerceAtMost(30_000L)115 }116 }117}118