Merge branch 'main' into development

This commit is contained in:
dasemu authored and GitHub committed 2026-10-26 06:48:25 +01:00
commit b6eeb62929
10 files changed
+232 -22

No files matched your search

@@ -33,17 +33,30 @@ internal data class MapDiagnosticEvent(
val connection: ConnectionState,
val androidApi: Int,
val appVersion: String = BuildConfig.VERSION_NAME,
val errorClass: String = "SDK_CALLBACK",
val sdkEvidence: String = "",
val firstTimestampMs: Long = timestampMs,
val occurrences: Int = 1,
val screenInteractive: Boolean? = null,
val lowMemory: Boolean? = null,
val availableMemoryMb: Long? = null,
) {
init {
require(timestampMs >= 0 && durationMs >= 0 && retryMs >= 0 && attempts in 1..4)
require(androidApi > 0 && appVersion.matches(Regex("[0-9]+(?:\\.[0-9]+){1,3}")))
require(availableMemoryMb == null || availableMemoryMb >= 0)
require(firstTimestampMs in 0..timestampMs && occurrences > 0)
require(errorClass.matches(Regex("[A-Za-z0-9_$]{1,80}")))
require(sdkEvidence.isEmpty() || sdkEvidence.matches(Regex("[A-Z_]{1,256}")))
require(httpStatus == null || httpStatus in 400..599)
require((kind == MapDiagnosticKind.FAILURE) == (failure != null))
}
fun reportLine(): String = "${Instant.ofEpochMilli(timestampMs)} · ${kind.name} · NavFrame $appVersion · Android $androidApi · MapLibre 13.5.2\n" +
"${source.name} · red ${network.name} · ${failure?.name ?: "OK"}/${stage.name} · ${resource.name}/${reason.name}${httpStatus?.let { "/HTTP_$it" } ?: ""}\n" +
"$durationMs ms · intento $attempts · reintento $retryMs ms · ${mode.name} · ${navigation.name} · TFT ${connection.name}"
"${source.name} · red ${network.name} · ${failure?.name ?: "OK"}/${stage.name} · ${resource.name}/${reason.name}${httpStatus?.let { "/HTTP_$it" } ?: ""}/$errorClass${if (sdkEvidence.isEmpty()) "" else "/WORDS_$sdkEvidence"}\n" +
"$durationMs ms · intento $attempts · reintento $retryMs ms · ${mode.name} · ${navigation.name} · TFT ${connection.name}" +
"\nPantalla ${screenInteractive?.let { if (it) "ENCENDIDA" else "APAGADA" } ?: "UNKNOWN"} · memoria baja ${lowMemory ?: "UNKNOWN"} · disponible ${availableMemoryMb ?: "UNKNOWN"} MiB" +
if (occurrences == 1) "" else "\nAgrupado: $occurrences fallos · primero ${Instant.ofEpochMilli(firstTimestampMs)} · último ${Instant.ofEpochMilli(timestampMs)} · estados del último fallo"
fun toJson(): JSONObject = JSONObject().put("kind", kind.name).put("timestampMs", timestampMs)
.put("source", source.name).put("network", network.name).put("stage", stage.name)
@@ -51,6 +64,10 @@ internal data class MapDiagnosticEvent(
.put("httpStatus", httpStatus ?: JSONObject.NULL).put("durationMs", durationMs).put("attempts", attempts)
.put("retryMs", retryMs).put("mode", mode.name).put("navigation", navigation.name)
.put("connection", connection.name).put("androidApi", androidApi).put("appVersion", appVersion)
.put("errorClass", errorClass).put("sdkEvidence", sdkEvidence)
.put("firstTimestampMs", firstTimestampMs).put("occurrences", occurrences)
.put("screenInteractive", screenInteractive ?: JSONObject.NULL).put("lowMemory", lowMemory ?: JSONObject.NULL)
.put("availableMemoryMb", availableMemoryMb ?: JSONObject.NULL)
companion object {
fun fromJson(value: JSONObject) = MapDiagnosticEvent(
@@ -64,6 +81,12 @@ internal data class MapDiagnosticEvent(
mode = NavigationMode.valueOf(value.getString("mode")), navigation = NavigationStatus.valueOf(value.getString("navigation")),
connection = ConnectionState.valueOf(value.getString("connection")), androidApi = value.getInt("androidApi"),
appVersion = value.getString("appVersion"),
errorClass = value.optString("errorClass", "SDK_CALLBACK"), sdkEvidence = value.optString("sdkEvidence", ""),
firstTimestampMs = value.optLong("firstTimestampMs", value.getLong("timestampMs")),
occurrences = value.optInt("occurrences", 1),
screenInteractive = if (value.isNull("screenInteractive")) null else value.getBoolean("screenInteractive"),
lowMemory = if (value.isNull("lowMemory")) null else value.getBoolean("lowMemory"),
availableMemoryMb = if (value.isNull("availableMemoryMb")) null else value.getLong("availableMemoryMb"),
)
}
}
@@ -78,7 +101,17 @@ internal class MapDiagnosticHistory(private val directory: File) {
try {
// An unreadable history cannot supply diagnostic text; the next event starts a clean history.
val previous = try { readEvents() } catch (_: Exception) { emptyList() }
val events = (previous + event).takeLast(MAX_EVENTS)
val last = previous.lastOrNull()
// Keep the initial retries, then summarize identical saturated retries without losing onset.
val repeated = last != null && event.kind == MapDiagnosticKind.FAILURE && last.kind == event.kind &&
last.attempts == 4 && event.attempts == 4 && event.timestampMs >= last.timestampMs &&
last.source == event.source && last.failure == event.failure && last.stage == event.stage &&
last.resource == event.resource && last.reason == event.reason && last.httpStatus == event.httpStatus &&
last.errorClass == event.errorClass && last.sdkEvidence == event.sdkEvidence &&
last.mode == event.mode && last.appVersion == event.appVersion && last.androidApi == event.androidApi
val events = if (repeated) previous.dropLast(1) + event.copy(
firstTimestampMs = last!!.firstTimestampMs, occurrences = (last.occurrences.toLong() + 1).coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
) else (previous + event).takeLast(MAX_EVENTS)
val bytes = JSONArray(events.map { it.toJson() }).toString().toByteArray(Charsets.UTF_8)
check(bytes.size <= MAX_BYTES)
val output = atomic.startWrite()
@@ -94,7 +94,9 @@ class MapLibreTftRenderer(context: Context, private val source: MapDataSource, p
})
}
}
phase(MapRenderStage.CAMERA_UPDATE)
current.setCameraPosition(cameraPosition)
phase(MapRenderStage.ROUTE_UPDATE)
(current.getSource("navframe-route") as? GeoJsonSource)?.setGeoJson(routeGeoJson(state.route))
continuation.invokeOnCancellation {
// An old callback must not be delivered into a new capture: discard after cancellation/error.
@@ -103,6 +105,7 @@ class MapLibreTftRenderer(context: Context, private val source: MapDataSource, p
}
try {
phase(if (current.getSource("navframe-route") == null) MapRenderStage.STYLE_LOADING else MapRenderStage.STYLE_READY)
phase(MapRenderStage.SNAPSHOT_REQUESTED)
current.start({ snapshot ->
if (continuation.isActive && !closed && snapshotter === current) phase(MapRenderStage.SNAPSHOT_READY)
val bitmap = snapshot.bitmap
@@ -120,7 +123,7 @@ class MapLibreTftRenderer(context: Context, private val source: MapDataSource, p
main.post {
current.cancel()
if (snapshotter === current) snapshotter = null
if (continuation.isActive) continuation.resumeWithException(MapRenderException(classifyMapRenderFailure(reason), stage, mapErrorDetail(reason)))
if (continuation.isActive) continuation.resumeWithException(MapRenderException(classifyMapRenderFailure(reason), stage, mapErrorDetail(reason, "SnapshotterErrorCallback")))
}
})
} catch (error: Exception) {
@@ -1,24 +1,26 @@
package dev.navframe.app
/** Only fixed labels cross this boundary; SDK messages can contain coordinates, URLs and access tokens. */
enum class MapRenderStage { INITIALIZE, STYLE_LOADING, STYLE_READY, SNAPSHOT_READY, COMPOSE }
enum class MapRenderStage { INITIALIZE, STYLE_LOADING, STYLE_READY, CAMERA_UPDATE, ROUTE_UPDATE, SNAPSHOT_REQUESTED, SNAPSHOT_READY, COMPOSE }
enum class MapRenderFailure { TIMEOUT, NETWORK, STYLE, GPU, BITMAP, SDK }
enum class MapResourceKind { GLYPH, SPRITE, TILE, GEOJSON, STYLE, BITMAP, UNKNOWN }
enum class MapFailureReason { DNS, FORBIDDEN, NOT_FOUND, CONTEXT_LOST, EGL, MEMORY, PARSE, CONNECTION, UNKNOWN }
data class MapErrorDetail(val resource: MapResourceKind = MapResourceKind.UNKNOWN, val reason: MapFailureReason = MapFailureReason.UNKNOWN, val httpStatus: Int? = null, val errorClass: String = "SDK_CALLBACK") {
fun safeText(): String = "${resource.name}/${reason.name}${httpStatus?.let { "/HTTP_$it" } ?: ""}/${errorClass.takeIf { it.matches(Regex("[A-Za-z0-9_$]{1,80}")) } ?: "OTHER"}"
enum class MapResourceKind { GLYPH, SPRITE, TILE, GEOJSON, STYLE, BITMAP, PMTILES, FILE, UNKNOWN }
enum class MapFailureReason { DNS, FORBIDDEN, NOT_FOUND, CONTEXT_LOST, EGL, MEMORY, PARSE, CONNECTION, IO, CANCELLED, EMPTY, UNSUPPORTED, UNKNOWN }
data class MapErrorDetail(val resource: MapResourceKind = MapResourceKind.UNKNOWN, val reason: MapFailureReason = MapFailureReason.UNKNOWN, val httpStatus: Int? = null, val errorClass: String = "SDK_CALLBACK", val sdkEvidence: String = "") {
fun safeText(): String = "${resource.name}/${reason.name}${httpStatus?.let { "/HTTP_$it" } ?: ""}/${errorClass.takeIf { it.matches(Regex("[A-Za-z0-9_$]{1,80}")) } ?: "OTHER"}${if (sdkEvidence.isEmpty()) "" else "/WORDS_${sdkEvidence}"}"
}
class MapRenderException(val failure: MapRenderFailure, val stage: MapRenderStage, val detail: MapErrorDetail = MapErrorDetail()) : Exception("${failure.name}:${stage.name}:${detail.safeText()}")
internal fun mapErrorDetail(message: String?, errorClass: String = "SDK_CALLBACK"): MapErrorDetail {
val text = message.orEmpty().lowercase(java.util.Locale.ROOT)
val status = Regex("\\b(?:http(?: status| error)?|status(?: code)?|server returned)\\D{0,12}([45]\\d{2})\\b").find(text)?.groupValues?.get(1)?.toIntOrNull()
val text = safeSdkEvidence(message).lowercase(java.util.Locale.ROOT).replace('_', ' ')
val status = Regex("\\b(?:http(?: status| error)?|status(?: code)?|server returned)\\D{0,12}([45]\\d{2})\\b").find(message.orEmpty().lowercase(java.util.Locale.ROOT))?.groupValues?.get(1)?.toIntOrNull()
val resource = when {
text.contains("pmtiles") -> MapResourceKind.PMTILES
listOf("glyph", "font").any(text::contains) -> MapResourceKind.GLYPH
text.contains("sprite") -> MapResourceKind.SPRITE
text.contains("geojson") -> MapResourceKind.GEOJSON
text.contains("tile") || text.contains(".pbf") -> MapResourceKind.TILE
text.contains("style") || text.contains("json") -> MapResourceKind.STYLE
text.contains("bitmap") || text.contains("canvas") -> MapResourceKind.BITMAP
text.contains("file") || text.contains("archive") -> MapResourceKind.FILE
else -> MapResourceKind.UNKNOWN
}
val reason = when {
@@ -30,12 +32,16 @@ internal fun mapErrorDetail(message: String?, errorClass: String = "SDK_CALLBACK
text.contains("memory") -> MapFailureReason.MEMORY
text.contains("parse") -> MapFailureReason.PARSE
text.contains("connection") || text.contains("socket") -> MapFailureReason.CONNECTION
text.contains("cancel") -> MapFailureReason.CANCELLED
text.contains("unsupported") || text.contains("not supported") -> MapFailureReason.UNSUPPORTED
text.contains("no such file") || text.contains("permission denied") || text.contains("read error") || text.contains("failed read") || text.contains("failed to read") || text.contains("failed open") || text.contains("failed to open") || text.contains("cannot read") || text.contains("cannot open") || text.contains("i/o") -> MapFailureReason.IO
message.isNullOrBlank() -> MapFailureReason.EMPTY
else -> MapFailureReason.UNKNOWN
}
return MapErrorDetail(resource, reason, status, errorClass)
return MapErrorDetail(resource, reason, status, errorClass, safeSdkEvidence(message))
}
internal fun classifyMapRenderFailure(message: String?): MapRenderFailure {
val text = message.orEmpty().lowercase(java.util.Locale.ROOT)
val text = safeSdkEvidence(message).lowercase(java.util.Locale.ROOT).replace('_', ' ')
return when {
listOf("egl", "opengl", "framebuffer", "shader", "gl context", "gl_context", "graphics context", "gpu").any(text::contains) -> MapRenderFailure.GPU
mapErrorDetail(message).httpStatus != null || listOf("resolve", "dns", "network", "connection", "socket", "server returned", "request failed", "failed to load resource", "failed to load tile", "failed to load glyph", "download").any(text::contains) -> MapRenderFailure.NETWORK
@@ -44,3 +50,16 @@ internal fun classifyMapRenderFailure(message: String?): MapRenderFailure {
else -> MapRenderFailure.SDK
}
}
/** Preserve only known diagnostic vocabulary, never arbitrary SDK text or identifiers. */
internal fun safeSdkEvidence(message: String?): String {
if (message.isNullOrBlank()) return "EMPTY"
val allowed = setOf("failed", "failure", "error", "exception", "load", "loading", "loaded", "style", "map", "snapshot", "snapshotter", "render", "rendering", "fully", "tile", "tiles", "data", "no", "not", "missing", "empty", "invalid", "corrupt", "unsupported", "resource", "request", "cancelled", "canceled", "cancel", "timeout", "timed", "out", "file", "archive", "pmtiles", "read", "write", "open", "permission", "denied", "such", "directory", "end", "unexpected", "parse", "parsing", "json", "geojson", "glyph", "glyphs", "font", "sprite", "image", "bitmap", "memory", "allocation", "context", "lost", "egl", "opengl", "framebuffer", "shader", "gpu", "network", "connection", "socket", "resolve", "dns", "http", "status", "code", "server", "returned", "forbidden", "found", "active", "already", "started", "finished", "destroyed", "source", "sources", "size", "dimensions", "download", "unable", "cannot", "could", "compression", "compressed", "gzip", "zstd", "protobuf", "decode", "decoding", "truncated", "eof", "i", "o", "to", "of", "is", "been", "has", "was", "be", "gl", "graphics", "canvas", "layer", "supported")
// Strip entire URLs, paths and quoted payloads before vocabulary extraction.
val stripped = message.lowercase(java.util.Locale.ROOT)
.replace(Regex("""[a-z][a-z0-9+.-]*://\S+"""), " ")
.replace(Regex("""[/\\]\S+"""), " ")
.replace(Regex("""["'][^"']*["']"""), " ")
val words = Regex("[a-z]+").findAll(stripped).map { it.value }.filter { it in allowed }.take(24).toList()
return if (words.isEmpty()) "UNCLASSIFIED" else words.joinToString("_").uppercase(java.util.Locale.ROOT).take(240).trimEnd('_')
}
@@ -825,13 +825,16 @@ class TftService : Service() {
mutableMapDiagnostic.value = "TFT MAP · ${error.failure.name} · ${error.stage.name} · ${SystemClock.elapsedRealtime() - mapRenderStarted} ms · ${error.detail.safeText()} · intento $mapFailures · reintento ${retryMs / 1000} s"
lastMapFailureDiagnostic = mutableMapDiagnostic.value + " · " + if (mapSource().uri.startsWith("file:")) "LOCAL" else "ONLINE"
mutableNavigationInfo.value = "MAPA TFT NO DISPONIBLE · ${error.failure.name} · reintento ${retryMs / 1000} s"
android.util.Log.w("NavFrame", "MAP_UNAVAILABLE code=${error.failure.name} stage=${error.stage.name} retryMs=$retryMs") // No URLs, API tokens or coordinates.
android.util.Log.w("NavFrame", "MAP_UNAVAILABLE code=${error.failure.name} stage=${error.stage.name} detail=${error.detail.safeText()} retryMs=$retryMs") // No URLs, API tokens or coordinates.
recordMapEvent(MapDiagnosticKind.FAILURE, state, mode, source, retryMs, error)
return MapFrameComposer().compose(null, null, state, mode, source.attribution, unavailable = true, failureCode = error.failure.name).also { unavailableMapFrame = it }
}
private suspend fun recordMapEvent(kind: MapDiagnosticKind, state: NavigationState, mode: NavigationMode, source: TileSource, retryMs: Long, error: MapRenderException? = null) {
val network = mapRenderer?.networkConnected ?: lastMapNetworkConnected
val memory = android.app.ActivityManager.MemoryInfo()
val memoryAvailable = runCatching { getSystemService(android.app.ActivityManager::class.java).getMemoryInfo(memory) }.isSuccess
val interactive = runCatching { getSystemService(android.os.PowerManager::class.java).isInteractive }.getOrNull()
val event = MapDiagnosticEvent(
kind = kind, timestampMs = System.currentTimeMillis(),
source = if (source.uri.startsWith("file:")) MapDiagnosticSource.LOCAL else MapDiagnosticSource.ONLINE,
@@ -839,6 +842,10 @@ class TftService : Service() {
stage = error?.stage ?: MapRenderStage.COMPOSE, failure = error?.failure,
resource = error?.detail?.resource ?: MapResourceKind.UNKNOWN, reason = error?.detail?.reason ?: MapFailureReason.UNKNOWN,
httpStatus = error?.detail?.httpStatus?.takeIf { it in 400..599 },
errorClass = error?.detail?.errorClass?.takeIf { it.matches(Regex("[A-Za-z0-9_$]{1,80}")) } ?: "OTHER",
sdkEvidence = error?.detail?.sdkEvidence.orEmpty(),
screenInteractive = interactive, lowMemory = if (memoryAvailable) memory.lowMemory else null,
availableMemoryMb = if (memoryAvailable) (memory.availMem / (1024 * 1024)).coerceAtLeast(0) else null,
durationMs = (SystemClock.elapsedRealtime() - mapRenderStarted).coerceAtLeast(0), attempts = mapFailures,
retryMs = retryMs, mode = mode, navigation = state.navigationStatus, connection = mutableState.value,
androidApi = Build.VERSION.SDK_INT,