package eu.friedcutlet.yokan.services.logging import eu.friedcutlet.yokan.util.nowMillis import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update internal data class NetworkStats( val requests: Long = 0, /** Transport failures (DNS, connect, timeout, cancellation), not HTTP status codes. */ val failures: Long = 0, /** Responses outside 200..399. */ val httpErrors: Long = 0, val bytesReceived: Long = 0, ) internal data class ImageStats( val memoryHits: Long = 0, val diskHits: Long = 0, val networkLoads: Long = 0, val errors: Long = 0, ) { val loads: Long get() = memoryHits + diskHits + networkLoads } /** Process-lifetime counters for Settings → Developer. Lock-free; they only ever grow. */ internal object Diagnostics { val startedAtMillis: Long = nowMillis() private val _network = MutableStateFlow(NetworkStats()) val network: StateFlow = _network.asStateFlow() private val _images = MutableStateFlow(ImageStats()) val images: StateFlow = _images.asStateFlow() fun recordResponse(statusCode: Int, bytes: Long) = _network.update { it.copy(requests = it.requests + 1, httpErrors = it.httpErrors + if (statusCode in 200..399) 0 else 1, bytesReceived = it.bytesReceived + bytes) } fun recordRequestFailure() = _network.update { it.copy(requests = it.requests + 1, failures = it.failures + 1) } fun recordImageMemoryHit() = _images.update { it.copy(memoryHits = it.memoryHits + 1) } fun recordImageDiskHit() = _images.update { it.copy(diskHits = it.diskHits + 1) } fun recordImageNetworkLoad() = _images.update { it.copy(networkLoads = it.networkLoads + 1) } fun recordImageError() = _images.update { it.copy(errors = it.errors + 1) } }