package eu.friedcutlet.yokan.services.sync import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.database.SyncServerProvider import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot import eu.friedcutlet.yokan.database.sync.SyncPaths import eu.friedcutlet.yokan.services.http.hubWebSocketBase import eu.friedcutlet.yokan.services.http.normalizeHubServer import eu.friedcutlet.yokan.services.logging.AppLogger import io.ktor.client.HttpClient import io.ktor.client.plugins.websocket.webSocket import io.ktor.client.request.header import io.ktor.http.HttpHeaders import io.ktor.websocket.Frame import io.ktor.websocket.readText import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.long /** `WS /api/v1/events` hints plus the debounced push after local edits, for [HubSyncService]. */ internal class HubLiveEvents( private val scope: CoroutineScope, private val liveClient: HttpClient?, private val leases: SyncAccountLeases, private val preference: (Long) -> DbSyncPreference?, private val round: suspend (syncId: Long) -> SyncResult, ) { private val json = SyncPaths.json private val stateMutex = Mutex() private var liveKey: LiveKey? = null private var liveJob: Job? = null private var pushJob: Job? = null private var lastOutboxSeq = -1L private data class LiveKey(val syncId: Long, val server: String, val token: String, val device: String) suspend fun onSnapshot(snapshot: YokanDatabaseSnapshot) { val pref = snapshot.syncPreferences.firstOrNull() val key = pref ?.takeIf { it.syncOn } ?.takeIf { it.serverProvider == SyncServerProvider.YokanHub } ?.let { p -> val token = p.authToken?.takeIf { it.isNotBlank() } ?: return@let null normalizeHubServer(p.server)?.let { LiveKey(p.syncId ?: 1L, it, token, p.deviceId ?: "unknown") } } val outboxSeq = snapshot.outbox.maxOfOrNull { it.seq } ?: 0L stateMutex.withLock { val keyChanged = key != liveKey if (keyChanged) { liveJob?.cancel() pushJob?.cancel() liveKey = key liveJob = if (key != null && liveClient != null) scope.launch { runLive(key) } else null } if (key != null && (outboxSeq > lastOutboxSeq || keyChanged && outboxSeq > 0)) schedulePushLocked(key.syncId) lastOutboxSeq = outboxSeq } } suspend fun stopLive() = stateMutex.withLock { liveJob?.cancel() liveJob = null liveKey = null } private fun schedulePushLocked(syncId: Long) { pushJob?.cancel() pushJob = scope.launch { delay(HubSyncService.PUSH_DEBOUNCE_MS) round(syncId) } } private suspend fun runLive(key: LiveKey) { val client = liveClient ?: return leases.claimFailure(preference(key.syncId))?.let { AppLogger.warn("[sync] hub live events not started: $it"); return } var backoff = 1_000L while (scope.isActive && stateMutex.withLock { liveKey == key }) { try { client.webSocket( urlString = hubWebSocketBase(key.server) + "/api/v1/events", request = { header(HttpHeaders.Authorization, "Bearer ${key.token}") header("X-Device", key.device) }, ) { backoff = 1_000L round(key.syncId) for (frame in incoming) { val text = (frame as? Frame.Text)?.readText() ?: continue val head = runCatching { json.parseToJsonElement(text).jsonObject["head"]?.jsonPrimitive?.long }.getOrNull() ?: continue if (head > (preference(key.syncId)?.hubHead ?: 0L)) round(key.syncId) } } } catch (cancelled: CancellationException) { throw cancelled } catch (error: Throwable) { // The REST round trip stays authoritative; a socket failure only delays hints. // Logged once per outage: the backoff only stays at its base until the first retry. if (backoff == 1_000L) { AppLogger.warn("[sync] hub live events disconnected: ${error.message?.lineSequence()?.firstOrNull() ?: error::class.simpleName}") } } if (!scope.isActive) break delay(backoff) backoff = (backoff * 2).coerceAtMost(30_000L) } } }