SyncClock.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncClock.kt
1package eu.friedcutlet.yokan.database.sync23import eu.friedcutlet.yokan.util.nowMillis4import kotlin.concurrent.atomics.AtomicLong5import kotlin.concurrent.atomics.ExperimentalAtomicApi67/**8 * Hybrid logical clock shared with the hub: 48 bits of wall-clock milliseconds, 16 bits of counter,9 * packed in one Long so it sorts numerically. Every outbox op gets a tick; every hub response is10 * observed so this device can never fall behind clocks it has already seen.11 */12@OptIn(ExperimentalAtomicApi::class)13object SyncClock {14 private val last = AtomicLong(0L)1516 fun pack(ms: Long, counter: Int): Long = (ms shl 16) or (counter.toLong() and 0xffff)17 fun millisOf(t: Long): Long = t ushr 1618 fun counterOf(t: Long): Int = (t and 0xffff).toInt()1920 fun tick(): Long {21 while (true) {22 val prev = last.load()23 val now = nowMillis()24 val next = when {25 now > millisOf(prev) -> pack(now, 0)26 counterOf(prev) == 0xffff -> pack(millisOf(prev) + 1, 0)27 else -> prev + 128 }29 if (last.compareAndSet(prev, next)) return next30 }31 }3233 fun observe(remote: Long) {34 while (true) {35 val prev = last.load()36 if (remote <= prev || last.compareAndSet(prev, remote)) return37 }38 }3940 fun peek(): Long = last.load()41}42