package eu.friedcutlet.yokan.database.sync import eu.friedcutlet.yokan.util.nowMillis import kotlin.concurrent.atomics.AtomicLong import kotlin.concurrent.atomics.ExperimentalAtomicApi /** * Hybrid logical clock shared with the hub: 48 bits of wall-clock milliseconds, 16 bits of counter, * packed in one Long so it sorts numerically. Every outbox op gets a tick; every hub response is * observed so this device can never fall behind clocks it has already seen. */ @OptIn(ExperimentalAtomicApi::class) object SyncClock { private val last = AtomicLong(0L) fun pack(ms: Long, counter: Int): Long = (ms shl 16) or (counter.toLong() and 0xffff) fun millisOf(t: Long): Long = t ushr 16 fun counterOf(t: Long): Int = (t and 0xffff).toInt() fun tick(): Long { while (true) { val prev = last.load() val now = nowMillis() val next = when { now > millisOf(prev) -> pack(now, 0) counterOf(prev) == 0xffff -> pack(millisOf(prev) + 1, 0) else -> prev + 1 } if (last.compareAndSet(prev, next)) return next } } fun observe(remote: Long) { while (true) { val prev = last.load() if (remote <= prev || last.compareAndSet(prev, remote)) return } } fun peek(): Long = last.load() }