Files
Klottr/shared/src/commonMain/kotlin/app/klottr/net/Geocache.kt
2025-09-22 18:44:29 +02:00

172 lines
5.8 KiB
Kotlin
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package app.klottr.net
import app.klottr.BuildKonfig
import app.klottr.util.AuthShared
import app.klottr.util.KLog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.withContext
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.math.floor
import kotlin.math.roundToInt
import kotlin.time.Clock
import kotlin.time.ExperimentalTime
/**
* Robust cache och hämtning av närliggande anslag.
*
* Offentlig API behålls: getNearby(lat, lon, radiusMeters, ttlMs)
* - Returnerar alltid en lista (ev. tom) och KASTAR INTE.
* - Använder intern cache per "ruta" (~110 m) så UI/Service får stabila svar.
* - Vid nätfel: faller tillbaka till cache (om det finns).
* - Om första hämtet blir tomt: gör EN omfråga utan cache (force refresh).
*/
object Geocache {
private data class Entry(
val timeMs: Long,
val items: List<NoteDTO>,
val etag: String?,
val sinceMs: Long
)
// KMP-säker cache: MutableMap + Mutex i stället för ConcurrentHashMap.
// Nyckel per “ruta” (0.001 grad ≈ 111 m) + radius-bucket (50 m steg)
private val cache = mutableMapOf<String, Entry>()
private val cacheMutex = Mutex()
/**
* Huvudmetod, kompatibel med v0.0.1.
*
* @param ttlMs hur länge vi litar på cache innan vi försöker hämta nytt
*/
@OptIn(ExperimentalTime::class)
suspend fun getNearby(
lat: Double,
lon: Double,
radiusMeters: Int,
ttlMs: Long
): List<NoteDTO> = withContext(Dispatchers.IO) {
val key = keyFor(lat, lon, radiusMeters)
val now = Clock.System.now().toEpochMilliseconds()
// 1) Snabbträff i giltig cache
val cached: Entry? = cacheMutex.withLock { cache[key] }
cached?.let { e ->
if ((now - e.timeMs) <= ttlMs) {
return@withContext e.items
}
}
// 2) Försök hämta nytt med ETag/since om vi har det
val prev = cached
val first = safeFetch(
lat = lat,
lon = lon,
radiusMeters = radiusMeters,
sinceMs = prev?.sinceMs ?: 0L,
etag = prev?.etag
)
if (first.code !in listOf(200, 304)) {
KLog.d { "Geocache: first fetch failed code=${first.code} → fallback to cache size=${prev?.items?.size ?: 0}" }
}
// Hantera 304/not-modified och nätfel (kod 599 i fetchNearby)
val firstItems = when (first.code) {
304 -> prev?.items.orEmpty()
200 -> first.items
else -> {
// Nätfel/annat → fall tillbaka till cache om vi har något
return@withContext prev?.items.orEmpty()
}
}
// Uppdatera cache efter första försöket
val firstSince = if (firstItems.isNotEmpty())
firstItems.maxOfOrNull { it.c } ?: (prev?.sinceMs ?: 0L)
else
(prev?.sinceMs ?: 0L)
cacheMutex.withLock {
cache[key] = Entry(
timeMs = now,
items = firstItems,
etag = first.etag ?: prev?.etag,
sinceMs = firstSince
)
}
// 3) Om listan är tom: gör EN omfråga utan cache/since (force refresh)
if (firstItems.isEmpty()) {
val fresh = safeFetch(
lat = lat,
lon = lon,
radiusMeters = radiusMeters,
sinceMs = 0L,
etag = null
)
val items = when (fresh.code) {
200 -> fresh.items
304 -> prev?.items.orEmpty() // borde inte inträffa utan etag, men säkra ändå
else -> prev?.items.orEmpty()
}
val since = if (items.isNotEmpty())
items.maxOfOrNull { it.c } ?: firstSince
else firstSince
cacheMutex.withLock {
cache[key] = Entry(
timeMs = now,
items = items,
etag = fresh.etag ?: first.etag ?: prev?.etag,
sinceMs = since
)
}
return@withContext items
}
return@withContext firstItems
}
// Skyddad fetch som aldrig kastar – använder KlottrApiShared.nearby från din KlottrApiShared.kt
private suspend fun safeFetch(
lat: Double,
lon: Double,
radiusMeters: Int,
sinceMs: Long,
etag: String?
): NearbyResult = try {
//TODO: OH: Call Shared directly for now, until Api.kt is fully migrated.
KlottrApiShared.nearby(
baseUrl = BuildKonfig.SERVER_API_BASE_URL,
apiKey = BuildKonfig.SERVER_API_KEY,
bearerToken = AuthShared.idToken,
lat = roundCoord(lat),
lon = roundCoord(lon),
radiusMeters = radiusMeters.coerceIn(50, 2000),
sinceMs = sinceMs,
lastEtag = etag,
limit = 200
)
} catch (_: Throwable) {
KLog.d { "nearby.php exception → code=599 lat=$lat lon=$lon r=$radiusMeters since=$sinceMs" }
NearbyResult(code = 599, items = emptyList(), etag = etag)
}
// Samma avrundning som du redan använder i UI när du sparar
private fun roundCoord(v: Double): Double = ((v * 1e6).roundToInt() / 1e6)
// Bygg en nyckel av "ruta" (0.001 grad) + radius bucket (avrundad till närmaste 50 m)
// Heltalsbaserad (milligrader) för att undvika String.format (JVM-only).
private fun keyFor(lat: Double, lon: Double, radiusMeters: Int): String {
val cellLatMilli = floor(lat * 1000.0).toInt()
val cellLonMilli = floor(lon * 1000.0).toInt()
val r = ((radiusMeters + 25) / 50) * 50 // 0..2000 i steg om 50
return "$cellLatMilli,$cellLonMilli|r=$r"
}
}