mirror of
https://github.com/Dasemu/NavFrame.git
synced 2026-11-26 07:16:06 +00:00
Merge branch 'main' into development
This commit is contained in:
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,
|
||||
|
||||
@@ -43,7 +43,8 @@ class MapDiagnosticHistoryTest {
|
||||
@Test fun committedFailuresAndRecoverySurviveNewStoreInstancesWithoutNativeMessages() {
|
||||
val raw = "Failed to load glyph https://private.example/fonts?token=secret HTTP status 403 at 43.361234,-5.856789"
|
||||
val detail = mapErrorDetail(raw)
|
||||
val failure = event().copy(failure = classifyMapRenderFailure(raw), resource = detail.resource, reason = detail.reason, httpStatus = detail.httpStatus)
|
||||
val failure = event().copy(failure = classifyMapRenderFailure(raw), resource = detail.resource, reason = detail.reason, httpStatus = detail.httpStatus,
|
||||
sdkEvidence = detail.sdkEvidence, errorClass = "SDK_CALLBACK", screenInteractive = false, lowMemory = true, availableMemoryMb = 42)
|
||||
assertTrue(store.record(failure))
|
||||
assertTrue(store.record(event(kind = MapDiagnosticKind.RECOVERED)))
|
||||
val reopened = MapDiagnosticHistory(context)
|
||||
@@ -72,6 +73,38 @@ class MapDiagnosticHistoryTest {
|
||||
assertFalse(store.file.exists())
|
||||
}
|
||||
|
||||
@Test fun repeatedSaturatedFailuresPreserveOnsetAndRecoveryInsteadOfEvictingIt() {
|
||||
for (index in 1..3) assertTrue(store.record(event(timestamp = index.toLong()).copy(attempts = index)))
|
||||
for (index in 4..204) assertTrue(store.record(event(timestamp = index.toLong()).copy(attempts = 4)))
|
||||
assertTrue(store.record(event(timestamp = 205, kind = MapDiagnosticKind.RECOVERED).copy(attempts = 4)))
|
||||
val report = MapDiagnosticHistory(context).report()
|
||||
assertTrue(report.contains("(5/100)"))
|
||||
assertTrue(report.contains("1970-01-01T00:00:00.001Z"))
|
||||
assertTrue(report.contains("Agrupado: 201 fallos"))
|
||||
assertTrue(report.contains("primero 1970-01-01T00:00:00.004Z"))
|
||||
assertTrue(report.contains("último 1970-01-01T00:00:00.204Z"))
|
||||
assertTrue(report.contains("RECOVERED"))
|
||||
assertTrue(store.record(event(timestamp = 206)))
|
||||
assertTrue(store.report().contains("(6/100)"))
|
||||
}
|
||||
|
||||
@Test fun legacyHistoryRemainsReadableAndNewEvidenceIsPersisted() {
|
||||
val json = event().toJson()
|
||||
for (key in listOf("errorClass", "sdkEvidence", "firstTimestampMs", "occurrences", "screenInteractive", "lowMemory", "availableMemoryMb")) json.remove(key)
|
||||
store.file.parentFile!!.mkdirs()
|
||||
store.file.writeText(org.json.JSONArray().put(json).toString())
|
||||
assertTrue(store.report().contains("TIMEOUT/STYLE_READY"))
|
||||
val raw = "Snapshot failed no tile data https://private.example?token=secret"
|
||||
val detail = mapErrorDetail(raw)
|
||||
assertTrue(store.record(event(timestamp = 1_792_000_000_001).copy(sdkEvidence = detail.sdkEvidence,
|
||||
screenInteractive = false, lowMemory = true, availableMemoryMb = 42)))
|
||||
val report = MapDiagnosticHistory(context).report()
|
||||
assertTrue(report.contains("WORDS_SNAPSHOT_FAILED_NO_TILE_DATA"))
|
||||
assertTrue(report.contains("Pantalla APAGADA"))
|
||||
assertTrue(report.contains("disponible 42 MiB"))
|
||||
assertFalse(store.file.readText().contains("private.example"))
|
||||
}
|
||||
|
||||
@Test fun interruptedAtomicReplacementLeavesTheLastCommittedHistoryReadable() {
|
||||
assertTrue(store.record(event()))
|
||||
val previous = store.report()
|
||||
|
||||
@@ -25,7 +25,7 @@ class MapRenderDiagnosticsTest {
|
||||
val raw = "Failed to load style glyph https://private.example/fonts.pbf?token=secret: HTTP status 403; location 43.361234,-5.856789"
|
||||
assertEquals(MapRenderFailure.NETWORK, classifyMapRenderFailure(raw))
|
||||
val detail = mapErrorDetail(raw)
|
||||
assertEquals("GLYPH/FORBIDDEN/HTTP_403/SDK_CALLBACK", detail.safeText())
|
||||
assertTrue(detail.safeText().startsWith("GLYPH/FORBIDDEN/HTTP_403/SDK_CALLBACK/WORDS_"))
|
||||
assertEquals(MapRenderFailure.NETWORK, classifyMapRenderFailure("Failed to load style: could not resolve private-host"))
|
||||
assertFalse(detail.safeText().contains("private"))
|
||||
assertFalse(detail.safeText().contains("secret"))
|
||||
@@ -40,4 +40,17 @@ class MapRenderDiagnosticsTest {
|
||||
assertEquals("TIMEOUT:STYLE_READY:UNKNOWN/UNKNOWN/SDK_CALLBACK", failure.message)
|
||||
assertNotEquals(MapRenderFailure.NETWORK, failure.failure)
|
||||
}
|
||||
@Test fun unknownCallbackRetainsOnlyDiagnosticVocabulary() {
|
||||
val raw = "Snapshot failed: no tile data private-address 43.361234,-5.856789 https://private.example/style?token=secret /data/user/0/private-map.pmtiles"
|
||||
val detail = mapErrorDetail(raw)
|
||||
assertEquals("SNAPSHOT_FAILED_NO_TILE_DATA", detail.sdkEvidence)
|
||||
assertEquals("EMPTY", mapErrorDetail(null).sdkEvidence)
|
||||
assertEquals(MapFailureReason.EMPTY, mapErrorDetail("").reason)
|
||||
assertEquals("UNCLASSIFIED", mapErrorDetail("private-secret-name").sdkEvidence)
|
||||
assertEquals(MapFailureReason.IO, mapErrorDetail("Cannot read PMTiles archive: permission denied").reason)
|
||||
assertEquals(MapResourceKind.PMTILES, mapErrorDetail("Cannot read PMTiles archive: permission denied").resource)
|
||||
assertTrue(safeSdkEvidence("failed ".repeat(1000)).length <= 240)
|
||||
assertEquals("FAILED", safeSdkEvidence("failed \"private map tile\" https://host/map/tile/43 /private/map/file"))
|
||||
}
|
||||
|
||||
}
|
||||
@@ -32,6 +32,9 @@ class RouteGuidanceTracker(private val route: RouteResult, private val config: G
|
||||
private var lastTimestamp: Long? = null
|
||||
private val outside = SustainedFixes()
|
||||
private val arrival = SustainedFixes()
|
||||
private val rejoin = SustainedFixes()
|
||||
private var importedDeviation = false
|
||||
private var rejoinProgress: Double? = null
|
||||
private var arrived = false
|
||||
private var needsRecovery = false
|
||||
private var lastState: NavigationState? = null
|
||||
@@ -45,7 +48,7 @@ class RouteGuidanceTracker(private val route: RouteResult, private val config: G
|
||||
fix.accuracyMeters.isFinite() && fix.accuracyMeters in 0f..config.maxAccuracyMeters &&
|
||||
(lastNow == null || nowMs >= lastNow!!)
|
||||
if (!usable) {
|
||||
outside.reset(); arrival.reset()
|
||||
outside.reset(); arrival.reset(); rejoin.reset(); rejoinProgress = null
|
||||
needsRecovery = lastPoint != null
|
||||
return remember(base.copy(speed = 0f, navigationStatus = NavigationStatus.GPS_LOST))
|
||||
}
|
||||
@@ -54,7 +57,7 @@ class RouteGuidanceTracker(private val route: RouteResult, private val config: G
|
||||
if (arrived) return remember(base.copy(speed = 0f, remainingDistanceMeters = 0,
|
||||
etaEpochMillis = if (route.imported) null else epochMs, navigationStatus = NavigationStatus.ARRIVED))
|
||||
if (needsRecovery || lastNow?.let { nowMs - it > config.maxFixAgeMs } == true) {
|
||||
outside.reset(); arrival.reset()
|
||||
outside.reset(); arrival.reset(); rejoin.reset(); rejoinProgress = null
|
||||
needsRecovery = false
|
||||
acquired = false
|
||||
lastPoint = fix.position
|
||||
@@ -71,11 +74,30 @@ class RouteGuidanceTracker(private val route: RouteResult, private val config: G
|
||||
lastNow = nowMs
|
||||
lastTimestamp = fix.timestampMs
|
||||
if (jumped) {
|
||||
outside.reset(); arrival.reset()
|
||||
outside.reset(); arrival.reset(); rejoin.reset(); rejoinProgress = null
|
||||
return remember(base.copy(speed = 0f, navigationStatus = NavigationStatus.GPS_LOST))
|
||||
}
|
||||
val projection = line.project(fix.position, progress, forwardAllowance)
|
||||
var projection = line.project(fix.position, progress, forwardAllowance)
|
||||
val outsideThreshold = max(config.offRouteMeters, fix.accuracyMeters * 2.0)
|
||||
if (route.imported && importedDeviation) {
|
||||
// A detour may rejoin anywhere on the original trace, including behind progress.
|
||||
// Require stable fresh fixes before widening the normal crossing-safe progress window.
|
||||
val candidate = line.project(fix.position, 0.0, line.total)
|
||||
val candidateProgress = candidate.local
|
||||
val stable = candidateProgress != null && candidate.localDistance <= outsideThreshold &&
|
||||
(rejoinProgress == null || abs(candidateProgress - rejoinProgress!!) <= movementAllowance)
|
||||
val confirmed = rejoin.observe(stable, distinct, nowMs, 3, 2_000)
|
||||
rejoinProgress = candidateProgress.takeIf { stable }
|
||||
if (!confirmed) {
|
||||
arrival.reset()
|
||||
return remember(base.copy(navigationStatus = NavigationStatus.OFF_ROUTE))
|
||||
}
|
||||
progress = requireNotNull(candidateProgress)
|
||||
acquired = true
|
||||
importedDeviation = false
|
||||
outside.reset(); rejoin.reset(); rejoinProgress = null
|
||||
projection = candidate
|
||||
}
|
||||
val offRoute = outside.observe(projection.localDistance > outsideThreshold, distinct, nowMs,
|
||||
config.offRouteFixes, config.offRouteDurationMs)
|
||||
// Freeze progress during inaccurate projection, so driving parallel to the road does not advance turns.
|
||||
@@ -84,6 +106,7 @@ class RouteGuidanceTracker(private val route: RouteResult, private val config: G
|
||||
acquired = true
|
||||
}
|
||||
if (offRoute) {
|
||||
if (route.imported) importedDeviation = true
|
||||
arrival.reset()
|
||||
return remember(base.copy(navigationStatus = NavigationStatus.OFF_ROUTE))
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package dev.navframe.core
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import kotlin.math.abs
|
||||
|
||||
class RouteGuidanceTest {
|
||||
// Equatorial segments are ~111.2m each; original route duration is 30 seconds.
|
||||
@@ -220,6 +221,82 @@ class RouteGuidanceTest {
|
||||
assertEquals(initial.remainingDistanceMeters, reversed.remainingDistanceMeters)
|
||||
}
|
||||
|
||||
private val importedTrace = RouteResult(
|
||||
listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.02)), emptyList(), 2224, 0, imported = true)
|
||||
|
||||
private fun deviatedImportedTracker(): RouteGuidanceTracker {
|
||||
val tracker = RouteGuidanceTracker(importedTrace)
|
||||
tracker.update(fix(lon = 0.005), 0, 0)
|
||||
tracker.update(fix(lat = -0.0007, lon = 0.005, time = 2), 3_000, 0)
|
||||
tracker.update(fix(lat = -0.0007, lon = 0.005, time = 3), 6_000, 0)
|
||||
val deviated = tracker.update(fix(lat = -0.0007, lon = 0.005, time = 4), 9_000, 0)
|
||||
assertEquals(NavigationStatus.OFF_ROUTE, deviated.navigationStatus)
|
||||
assertSame(importedTrace, deviated.route)
|
||||
return tracker
|
||||
}
|
||||
|
||||
@Test fun `imported detour rejoins ahead or behind frozen progress without replacing trace`() {
|
||||
for (longitude in listOf(0.012, 0.002)) {
|
||||
val tracker = deviatedImportedTracker()
|
||||
// The isolated relocation is rejected. Stable fixes then reacquire the original trace.
|
||||
assertEquals(NavigationStatus.GPS_LOST,
|
||||
tracker.update(fix(lon = longitude, time = 5), 10_000, 0).navigationStatus)
|
||||
for (i in 6L..7L) {
|
||||
assertEquals(NavigationStatus.OFF_ROUTE,
|
||||
tracker.update(fix(lon = longitude, time = i), (i + 5) * 1_000, 0).navigationStatus)
|
||||
}
|
||||
val resumed = tracker.update(fix(lon = longitude, time = 8), 13_000, 0)
|
||||
assertEquals(NavigationStatus.NAVIGATING, resumed.navigationStatus)
|
||||
assertTrue(abs(((0.02 - longitude) * 111_195) - resumed.remainingDistanceMeters!!) < 1)
|
||||
assertSame(importedTrace, resumed.route)
|
||||
assertNull(resumed.nextManeuver)
|
||||
assertNull(resumed.etaEpochMillis)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun `repeated stale and inaccurate fixes cannot confirm imported rejoin`() {
|
||||
val tracker = deviatedImportedTracker()
|
||||
tracker.update(fix(lon = 0.012, time = 5), 10_000, 0)
|
||||
val candidate = fix(lon = 0.012, time = 6)
|
||||
assertEquals(NavigationStatus.OFF_ROUTE, tracker.update(candidate, 11_000, 0).navigationStatus)
|
||||
assertEquals(NavigationStatus.OFF_ROUTE, tracker.update(candidate, 14_000, 0).navigationStatus)
|
||||
assertEquals(NavigationStatus.GPS_LOST,
|
||||
tracker.update(fix(lon = 0.012, time = 7, accuracy = 40f), 15_000, 0).navigationStatus)
|
||||
assertEquals(NavigationStatus.GPS_LOST,
|
||||
tracker.update(fix(lon = 0.012, time = 8), 16_000, 0, 15_001).navigationStatus)
|
||||
tracker.update(fix(lon = 0.012, time = 9), 17_000, 0)
|
||||
tracker.update(fix(lon = 0.012, time = 10), 18_000, 0)
|
||||
tracker.update(fix(lon = 0.012, time = 11), 19_000, 0)
|
||||
assertEquals(NavigationStatus.NAVIGATING,
|
||||
tracker.update(fix(lon = 0.012, time = 12), 20_000, 0).navigationStatus)
|
||||
}
|
||||
|
||||
@Test fun `closed imported trace rejoin at shared start and finish cannot falsely arrive`() {
|
||||
val loop = importedTrace.copy(geometry = listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.002),
|
||||
GeoPoint(0.002, 0.002), GeoPoint(0.002, 0.0), GeoPoint(0.0, 0.0)))
|
||||
val tracker = RouteGuidanceTracker(loop)
|
||||
tracker.update(fix(lon = 0.0005), 0, 0)
|
||||
for (i in 2L..4L) tracker.update(fix(lat = -0.0007, lon = 0.0005, time = i), (i - 1) * 3_000, 0)
|
||||
for (i in 5L..9L) {
|
||||
val state = tracker.update(fix(time = i), (i + 5) * 1_000, 0)
|
||||
assertNotEquals(NavigationStatus.ARRIVED, state.navigationStatus)
|
||||
if (i >= 7) {
|
||||
assertEquals(NavigationStatus.NAVIGATING, state.navigationStatus)
|
||||
assertTrue(state.remainingDistanceMeters!! > 800)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun `imported crossing preserves progress until deviation is sustained`() {
|
||||
val crossing = importedTrace.copy(geometry = listOf(GeoPoint(0.0, 0.0), GeoPoint(0.0, 0.002),
|
||||
GeoPoint(0.002, 0.002), GeoPoint(0.002, 0.0), GeoPoint(0.0, 0.0), GeoPoint(0.0, -0.002)))
|
||||
val tracker = RouteGuidanceTracker(crossing)
|
||||
val initial = tracker.update(fix(), 0, 0)
|
||||
val next = tracker.update(fix(lon = -0.00005, time = 2), 1_000, 0)
|
||||
assertEquals(initial.remainingDistanceMeters, next.remainingDistanceMeters)
|
||||
assertEquals(NavigationStatus.NAVIGATING, next.navigationStatus)
|
||||
}
|
||||
|
||||
@Test fun `maneuver arrows use type rather than translated prose`() {
|
||||
assertEquals(ManeuverDirection.LEFT, maneuverDirection(15))
|
||||
assertEquals(ManeuverDirection.RIGHT, maneuverDirection(10))
|
||||
|
||||
@@ -14,7 +14,7 @@ Files are limited to 5 MiB, 10,000 total route and track points and 64 XML nesti
|
||||
|
||||
The original coordinates are retained locally in memory and drawn on the phone and TFT. GPX import does not send the file or its coordinates to a routing server. It works with the installed offline map; online background tiles still require a connection when no offline map is selected. Standard trace points do not establish legal roads, surface quality, reliable turns or travel time.
|
||||
|
||||
The display says **Sigue el trazado GPX**. It shows progress, remaining distance, sustained deviations and arrival using the existing GPS guidance policy. It does not invent turn instructions, speak turn announcements, show an ETA, or automatically reroute away from the imported trace. On a deviation, return to the trace using the map and road signs. Manual recalculation also preserves the trace.
|
||||
The display says **Sigue el trazado GPX**. It shows progress, remaining distance, sustained deviations and arrival using the existing GPS guidance policy. It does not invent turn instructions, speak turn announcements, show an ETA, or automatically reroute away from the imported trace. On a deviation, return to the trace using the map and road signs. Manual recalculation also preserves the trace. After a confirmed deviation, three fresh, stable GPS fixes spanning at least two seconds automatically resume progress at the nearest point of the original trace, whether you rejoin ahead of or behind the previous position. GPS jumps and inaccurate fixes cannot confirm a rejoin.
|
||||
|
||||
The imported route is not persisted across process death or device reboot: reload the original document to resume. The document remains in its selected provider; the app does not request long-term file access or copy the GPX into its own storage. Map diagnostics do not include route coordinates, document paths or route names.
|
||||
|
||||
|
||||
@@ -14,11 +14,13 @@ Each event contains its UTC timestamp, app version, Android API level, MapLibre
|
||||
|
||||
The backoff attempt is capped at four, like the renderer's existing retry policy. Repeated failures continue to create separate timestamped records after that limit. Only the first successful render following failures creates a recovery record; normal successful frames are not logged.
|
||||
|
||||
From 0.13.6, diagnostics also retain the callback/exception class, a bounded sequence of allowlisted SDK diagnostic words (`WORDS_...`), screen interactive state, low-memory status and available system memory. Render stages distinguish camera updates, route GeoJSON updates and snapshot requests; native snapshot failure callbacks carry `SnapshotterErrorCallback` rather than the generic `SDK_CALLBACK`. URL/path/quoted payloads are removed before extracting known diagnostic words. An empty callback is distinguished from an unclassified nonempty message. This exposes messages such as snapshot/failed/no/tile/data without copying arbitrary SDK text. These fields are evidence, not proof that memory or screen state caused the failure.
|
||||
|
||||
Raw SDK messages, stack traces, URLs, tokens, coordinates, route geometry, destinations, search text, and Bluetooth identifiers are excluded. The history contains fixed labels and numbers, not a copy of Logcat. Network state is diagnostic context: a disconnected network does not itself explain a failure of a selected local map.
|
||||
|
||||
## Storage and limits
|
||||
|
||||
The history is a private app file named `tft-map-diagnostics.json` in Android's `noBackupFilesDir`. No storage permission is required; the app does not upload it automatically, and it is excluded from backup/device transfer. The file retains the latest 100 failure/recovery events and is bounded at 128 KiB. Older events are discarded when the limit is reached.
|
||||
The history is a private app file named `tft-map-diagnostics.json` in Android's `noBackupFilesDir`. No storage permission is required; the app does not upload it automatically, and it is excluded from backup/device transfer. The file retains up to 100 failure/recovery records and is bounded at 128 KiB. Starting with 0.13.6, consecutive identical failures at the maximum retry backoff are grouped into one record with an occurrence count and first/last UTC timestamps. Initial retries and recovery records remain separate; the aggregate shows the latest navigation, network and TFT states. Changes in error classification, source, mode or app version start a new record. This prevents a long stream of identical failures from immediately erasing its onset. Older records are discarded when the limit is reached. Existing 0.13.2–0.13.5 files remain readable; previously evicted events cannot be recovered.
|
||||
|
||||
File operations run on an IO dispatcher. Writes are synced and replaced atomically, so an interrupted replacement preserves the previous completed history. A failure that occurs while a shutdown interrupts its write may not be retained. Clearing app data or uninstalling NavFrame deletes the history.
|
||||
|
||||
|
||||
Reference in new issue
Block a user