Skip to content

A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.

fix(data): resilient settings reads, port-forward de-dup, update-check logic

ExTv9f184b39b6fc
diff --git a/app/src/main/java/com/excp/podroid/data/repository/PortForwardRepository.kt b/app/src/main/java/com/excp/podroid/data/repository/PortForwardRepository.kt
index b81c78e..210b838 100644
--- a/app/src/main/java/com/excp/podroid/data/repository/PortForwardRepository.kt
+++ b/app/src/main/java/com/excp/podroid/data/repository/PortForwardRepository.kt
@@ -8,12 +8,15 @@ package com.excp.podroid.data.repository
import android.content.Context
import androidx.datastore.preferences.core.edit
+import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.stringSetPreferencesKey
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
+import java.io.IOException
import javax.inject.Inject
import javax.inject.Singleton
@@ -31,17 +34,44 @@ data class PortForwardRule(
fun serialize(): String = "$protocol:$hostPort:$guestPort"
companion object {
+ private val VALID_PROTOCOLS = setOf("tcp", "udp")
+
fun deserialize(s: String): PortForwardRule? {
val parts = s.split(":")
if (parts.size != 3) return null
val proto = parts[0]
+ if (proto !in VALID_PROTOCOLS) return null
val host = parts[1].toIntOrNull() ?: return null
val guest = parts[2].toIntOrNull() ?: return null
+ if (host !in 1..65535 || guest !in 1..65535) return null
return PortForwardRule(host, guest, proto)
}
}
}
+/**
+ * Removes any existing entry in [current] that shares the same
+ * (hostPort, protocol) key as [newRule], then adds [newRule].
+ *
+ * The engine and UI treat (hostPort, protocol) as a unique key — two rules
+ * with the same host port and protocol would produce duplicate QEMU hostfwd
+ * arguments and a duplicate Compose key crash.
+ */
+internal fun deduplicatePortForwards(
+ current: Set<String>,
+ newRule: PortForwardRule,
+): Set<String> {
+ val filtered = current.filterTo(mutableSetOf()) { serialized ->
+ val existing = PortForwardRule.deserialize(serialized)
+ // Keep entries that differ in either hostPort or protocol.
+ existing == null ||
+ existing.hostPort != newRule.hostPort ||
+ existing.protocol != newRule.protocol
+ }
+ filtered.add(newRule.serialize())
+ return filtered
+}
+
@Singleton
class PortForwardRepository @Inject constructor(
@ApplicationContext private val context: Context,
@@ -51,18 +81,19 @@ class PortForwardRepository @Inject constructor(
}
val rules: Flow<List<PortForwardRule>> = context.dataStore.data
+ .catch { e -> if (e is IOException) emit(emptyPreferences()) else throw e }
.map { prefs ->
prefs[KEY_PORT_FORWARDS]
?.mapNotNull { PortForwardRule.deserialize(it) }
+ ?.sortedWith(compareBy({ it.hostPort }, { it.protocol }))
?: emptyList()
}
.distinctUntilChanged()
suspend fun addRule(rule: PortForwardRule) {
context.dataStore.edit { prefs ->
- val current = prefs[KEY_PORT_FORWARDS]?.toMutableSet() ?: mutableSetOf()
- current.add(rule.serialize())
- prefs[KEY_PORT_FORWARDS] = current
+ val current = prefs[KEY_PORT_FORWARDS] ?: emptySet()
+ prefs[KEY_PORT_FORWARDS] = deduplicatePortForwards(current, rule)
}
}
@@ -75,9 +106,11 @@ class PortForwardRepository @Inject constructor(
}
suspend fun getRulesSnapshot(): List<PortForwardRule> =
- context.dataStore.data.map { prefs ->
- prefs[KEY_PORT_FORWARDS]
- ?.mapNotNull { PortForwardRule.deserialize(it) }
- ?: emptyList()
- }.first()
+ context.dataStore.data
+ .catch { e -> if (e is IOException) emit(emptyPreferences()) else throw e }
+ .map { prefs ->
+ prefs[KEY_PORT_FORWARDS]
+ ?.mapNotNull { PortForwardRule.deserialize(it) }
+ ?: emptyList()
+ }.first()
}
diff --git a/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt b/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt
index e10646d..720667d 100644
--- a/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt
+++ b/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt
@@ -18,8 +18,10 @@ import androidx.datastore.preferences.preferencesDataStore
import com.excp.podroid.engine.EngineSelection
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
+import java.io.IOException
import javax.inject.Inject
import javax.inject.Singleton
@@ -93,7 +95,9 @@ class SettingsRepository @Inject constructor(
}
private fun <T> pref(key: Preferences.Key<T>, default: T): Flow<T> =
- context.dataStore.data.map { it[key] ?: default }
+ context.dataStore.data
+ .catch { e -> if (e is IOException) emit(androidx.datastore.preferences.core.emptyPreferences()) else throw e }
+ .map { it[key] ?: default }
private suspend fun <T> set(key: Preferences.Key<T>, value: T) =
context.dataStore.edit { it[key] = value }
@@ -120,13 +124,15 @@ class SettingsRepository @Inject constructor(
val dynamicColorEnabled = pref(KEY_DYNAMIC_COLOR_ENABLED, false)
val lastBootDurationMs = pref(KEY_LAST_BOOT_DURATION_MS, 0L)
val avfHintDismissed = pref(KEY_AVF_HINT_DISMISSED, false)
- val avfVerboseLogging: Flow<Boolean> = context.dataStore.data.map { prefs ->
- prefs[KEY_AVF_VERBOSE_LOGGING] ?: false
- }
- val engineSelection: Flow<EngineSelection> = context.dataStore.data.map { prefs ->
- runCatching { EngineSelection.valueOf(prefs[KEY_ENGINE_SELECTION] ?: "AUTO") }
- .getOrDefault(EngineSelection.AUTO)
- }
+ val avfVerboseLogging: Flow<Boolean> = context.dataStore.data
+ .catch { e -> if (e is IOException) emit(androidx.datastore.preferences.core.emptyPreferences()) else throw e }
+ .map { prefs -> prefs[KEY_AVF_VERBOSE_LOGGING] ?: false }
+ val engineSelection: Flow<EngineSelection> = context.dataStore.data
+ .catch { e -> if (e is IOException) emit(androidx.datastore.preferences.core.emptyPreferences()) else throw e }
+ .map { prefs ->
+ runCatching { EngineSelection.valueOf(prefs[KEY_ENGINE_SELECTION] ?: "AUTO") }
+ .getOrDefault(EngineSelection.AUTO)
+ }
suspend fun setDarkTheme(value: Boolean) = set(KEY_DARK_THEME, value)
suspend fun setVmRamMb(value: Int) = set(KEY_VM_RAM, value)
@@ -148,7 +154,9 @@ class SettingsRepository @Inject constructor(
suspend fun setAvfHintDismissed(value: Boolean) = set(KEY_AVF_HINT_DISMISSED, value)
suspend fun setAvfVerboseLogging(value: Boolean) = set(KEY_AVF_VERBOSE_LOGGING, value)
- val x11Settings: kotlinx.coroutines.flow.Flow<com.excp.podroid.x11.X11Settings> = context.dataStore.data.map { p ->
+ val x11Settings: kotlinx.coroutines.flow.Flow<com.excp.podroid.x11.X11Settings> = context.dataStore.data
+ .catch { e -> if (e is IOException) emit(androidx.datastore.preferences.core.emptyPreferences()) else throw e }
+ .map { p ->
com.excp.podroid.x11.X11Settings(
resolutionMode = runCatching { com.excp.podroid.x11.ResolutionMode.valueOf(p[KEY_X11_RES_MODE] ?: "MATCH") }.getOrDefault(com.excp.podroid.x11.ResolutionMode.MATCH),
preset = runCatching { com.excp.podroid.x11.ResolutionPreset.valueOf(p[KEY_X11_RES_PRESET] ?: "R1080P") }.getOrDefault(com.excp.podroid.x11.ResolutionPreset.R1080P),
@@ -166,7 +174,9 @@ class SettingsRepository @Inject constructor(
suspend fun setX11ResolutionMode(v: String) = set(KEY_X11_RES_MODE, v)
suspend fun setX11Preset(v: String) = set(KEY_X11_RES_PRESET, v)
- suspend fun setX11Custom(w: Int, h: Int) { set(KEY_X11_CUSTOM_W, w); set(KEY_X11_CUSTOM_H, h) }
+ suspend fun setX11Custom(w: Int, h: Int) {
+ context.dataStore.edit { it[KEY_X11_CUSTOM_W] = w; it[KEY_X11_CUSTOM_H] = h }
+ }
suspend fun setX11TouchMode(v: String) = set(KEY_X11_TOUCH_MODE, v)
suspend fun setX11TrackpadSensitivity(v: Float) = set(KEY_X11_TP_SENSITIVITY, v.toString())
suspend fun setX11TrackpadAccel(v: Boolean) = set(KEY_X11_TP_ACCEL, v)
diff --git a/app/src/main/java/com/excp/podroid/data/repository/UpdateRepository.kt b/app/src/main/java/com/excp/podroid/data/repository/UpdateRepository.kt
index 6761454..4f511ac 100644
--- a/app/src/main/java/com/excp/podroid/data/repository/UpdateRepository.kt
+++ b/app/src/main/java/com/excp/podroid/data/repository/UpdateRepository.kt
@@ -1,7 +1,6 @@
package com.excp.podroid.data.repository
import android.content.Context
-import android.os.SystemClock
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
@@ -19,6 +18,93 @@ data class UpdateInfo(
val releaseUrl: String,
)
+/**
+ * Returns true when the cache has expired and a fresh network check is warranted.
+ *
+ * Uses wall-clock milliseconds (currentTimeMillis) — not uptimeMillis, which
+ * resets to zero on reboot and causes the post-reboot delta to be a large
+ * negative number, permanently skipping the check. A negative delta is clamped
+ * to "stale" so a clock going backwards also triggers a re-check rather than
+ * suppressing it indefinitely.
+ */
+internal fun shouldCheck(now: Long, lastCheck: Long, validityMs: Long): Boolean {
+ val elapsed = now - lastCheck
+ return elapsed < 0L || elapsed >= validityMs
+}
+
+/**
+ * Returns true if `latest` is a higher version than `current`. Compares the
+ * numeric core (`1.2.3`) first; if those are equal, treats a prerelease suffix
+ * (`-rc2`) as lower than a release, and compares prerelease numeric chunks
+ * numerically so `rc10 > rc9`.
+ */
+internal fun isNewer(latest: String, current: String): Boolean {
+ fun splitCore(v: String) = v.substringBefore("-").split(".").map { it.toIntOrNull() ?: 0 }
+ val l = splitCore(latest)
+ val c = splitCore(current)
+ val maxLen = maxOf(l.size, c.size)
+ for (i in 0 until maxLen) {
+ val lv = l.getOrElse(i) { 0 }
+ val cv = c.getOrElse(i) { 0 }
+ if (lv > cv) return true
+ if (lv < cv) return false
+ }
+ // Numeric cores match — break ties by suffix. Empty suffix > any prerelease suffix.
+ val ls = latest.substringAfter("-", "")
+ val cs = current.substringAfter("-", "")
+ return when {
+ ls == cs -> false
+ ls.isEmpty() -> true // "1.2.0" is newer than "1.2.0-rc1"
+ cs.isEmpty() -> false // "1.2.0-rc1" is older than "1.2.0"
+ else -> comparePrerelease(ls, cs) > 0
+ }
+}
+
+/**
+ * Compares two prerelease strings (the part after `-`) by splitting on
+ * non-numeric/numeric boundaries and comparing each chunk: numeric chunks
+ * compare as integers, non-numeric chunks compare lexicographically.
+ * Example: "rc10" > "rc9" because the numeric chunk 10 > 9.
+ */
+private fun comparePrerelease(a: String, b: String): Int {
+ fun chunks(s: String): List<String> = buildList {
+ val sb = StringBuilder()
+ var numeric = s.firstOrNull()?.isDigit() ?: false
+ for (ch in s) {
+ if (ch.isDigit() == numeric) {
+ sb.append(ch)
+ } else {
+ if (sb.isNotEmpty()) add(sb.toString())
+ sb.clear()
+ sb.append(ch)
+ numeric = ch.isDigit()
+ }
+ }
+ if (sb.isNotEmpty()) add(sb.toString())
+ }
+
+ val ac = chunks(a)
+ val bc = chunks(b)
+ val len = maxOf(ac.size, bc.size)
+ for (i in 0 until len) {
+ val ac_ = ac.getOrElse(i) { "" }
+ val bc_ = bc.getOrElse(i) { "" }
+ val cmp = when {
+ ac_.isEmpty() && bc_.isEmpty() -> 0
+ ac_.isEmpty() -> -1
+ bc_.isEmpty() -> 1
+ ac_.all { it.isDigit() } && bc_.all { it.isDigit() } ->
+ // Clamp oversized numeric chunks to lexicographic so a malformed
+ // tag (>18 digits, > Long.MAX) can't throw NumberFormatException.
+ if (ac_.length <= 18 && bc_.length <= 18) ac_.toLong().compareTo(bc_.toLong())
+ else ac_.compareTo(bc_)
+ else -> ac_.compareTo(bc_)
+ }
+ if (cmp != 0) return cmp
+ }
+ return 0
+}
+
@Singleton
class UpdateRepository @Inject constructor(
@ApplicationContext private val context: Context,
@@ -28,30 +114,39 @@ class UpdateRepository @Inject constructor(
private val cacheValidityMs = 24 * 60 * 60 * 1000L
suspend fun checkForUpdate(currentVersion: String): UpdateInfo? = withContext(Dispatchers.IO) {
- try {
- // Monotonic clock — immune to NTP jumps and manual user clock changes,
- // both of which can leave the cache effectively pinned or instantly stale.
- val now = SystemClock.uptimeMillis()
- val lastCheck = context.dataStore.data.first()[lastCheckKey] ?: 0L
+ // Wall-clock time so the 24h gate survives device reboots and deep sleep.
+ val now = System.currentTimeMillis()
+ val lastCheck = context.dataStore.data.first()[lastCheckKey] ?: 0L
- if (now - lastCheck < cacheValidityMs) {
- return@withContext null
- }
+ if (!shouldCheck(now, lastCheck, cacheValidityMs)) {
+ return@withContext null
+ }
- val connection = URL("https://api.github.com/repos/ExTV/Podroid/releases/latest")
- .openConnection() as java.net.HttpURLConnection
+ val connection = URL("https://api.github.com/repos/ExTV/Podroid/releases/latest")
+ .openConnection() as java.net.HttpURLConnection
+ try {
connection.connectTimeout = 5000
connection.readTimeout = 5000
connection.setRequestProperty("Accept", "application/vnd.github+json")
- val json = try {
- connection.inputStream.bufferedReader().use { it.readText() }
- } finally {
- connection.disconnect()
+
+ val code = connection.responseCode
+ if (code !in 200..299) {
+ // Consume error body so the connection can be reused, then back off.
+ runCatching { connection.errorStream?.bufferedReader()?.use { it.readText() } }
+ context.dataStore.edit { it[lastCheckKey] = now }
+ return@withContext null
}
+ val json = connection.inputStream.bufferedReader().use { it.readText() }
val obj = JSONObject(json)
- val tag = obj.getString("tag_name").trimStart('v')
- val url = obj.getString("html_url")
+ // removePrefix rather than trimStart — trimStart strips repeated 'v' chars.
+ val tag = obj.optString("tag_name", "").removePrefix("v")
+ val url = obj.optString("html_url", "")
+
+ if (tag.isEmpty() || url.isEmpty()) {
+ context.dataStore.edit { it[lastCheckKey] = now }
+ return@withContext null
+ }
context.dataStore.edit { it[lastCheckKey] = now }
@@ -60,7 +155,11 @@ class UpdateRepository @Inject constructor(
val normalizedCurrent = currentVersion.removeSuffix("-debug")
if (isNewer(tag, normalizedCurrent)) UpdateInfo(tag, url) else null
} catch (_: Exception) {
+ // Network error: still record the timestamp to back off on the next launch.
+ runCatching { context.dataStore.edit { it[lastCheckKey] = now } }
null
+ } finally {
+ connection.disconnect()
}
}
@@ -72,32 +171,4 @@ class UpdateRepository @Inject constructor(
suspend fun dismissUpdate(version: String) {
context.dataStore.edit { it[dismissedKey] = version }
}
-
- /**
- * Returns true if `latest` is a higher version than `current`. Compares the
- * numeric core (`1.2.3`) first; if those are equal, treats a prerelease
- * suffix (`-rc2`) as lower than a release, and falls back to lexicographic
- * comparison of the suffixes themselves so 1.2.0-rc2 > 1.2.0-rc1.
- */
- private fun isNewer(latest: String, current: String): Boolean {
- fun split(v: String) = v.substringBefore("-").split(".").map { it.toIntOrNull() ?: 0 }
- val l = split(latest)
- val c = split(current)
- val maxLen = maxOf(l.size, c.size)
- for (i in 0 until maxLen) {
- val lv = l.getOrElse(i) { 0 }
- val cv = c.getOrElse(i) { 0 }
- if (lv > cv) return true
- if (lv < cv) return false
- }
- // Numeric cores match — break ties by suffix. Empty suffix > any prerelease suffix.
- val ls = latest.substringAfter("-", "")
- val cs = current.substringAfter("-", "")
- return when {
- ls == cs -> false
- ls.isEmpty() -> true // "1.2.0" is newer than "1.2.0-rc1"
- cs.isEmpty() -> false // "1.2.0-rc1" is older than "1.2.0"
- else -> ls > cs // lexicographic compare for ordered prereleases
- }
- }
}
diff --git a/app/src/test/java/com/excp/podroid/data/repository/PortForwardRepositoryTest.kt b/app/src/test/java/com/excp/podroid/data/repository/PortForwardRepositoryTest.kt
new file mode 100644
index 0000000..b7acdee
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/data/repository/PortForwardRepositoryTest.kt
@@ -0,0 +1,133 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ *
+ * Unit tests for PortForwardRule pure logic and dedup helper.
+ */
+package com.excp.podroid.data.repository
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+/**
+ * Bug 4: PortForwardRule.deserialize must validate protocol and port range.
+ * Bug 5: addRule must dedup on (hostPort, protocol) key.
+ */
+class PortForwardRepositoryTest {
+
+ // ------------------------------------------------------------------
+ // Bug 4 — deserialize validation
+ // ------------------------------------------------------------------
+
+ @Test
+ fun `deserialize valid tcp rule round-trips`() {
+ val rule = PortForwardRule(8080, 80, "tcp")
+ val result = PortForwardRule.deserialize(rule.serialize())
+ assertNotNull(result)
+ assertEquals(rule, result)
+ }
+
+ @Test
+ fun `deserialize valid udp rule round-trips`() {
+ val rule = PortForwardRule(9922, 22, "udp")
+ val result = PortForwardRule.deserialize(rule.serialize())
+ assertNotNull(result)
+ assertEquals(rule, result)
+ }
+
+ @Test
+ fun `deserialize rejects unknown protocol`() {
+ assertNull(PortForwardRule.deserialize("sctp:8080:80"))
+ }
+
+ @Test
+ fun `deserialize rejects port zero`() {
+ assertNull(PortForwardRule.deserialize("tcp:0:80"))
+ }
+
+ @Test
+ fun `deserialize rejects guest port zero`() {
+ assertNull(PortForwardRule.deserialize("tcp:8080:0"))
+ }
+
+ @Test
+ fun `deserialize rejects port above 65535`() {
+ assertNull(PortForwardRule.deserialize("tcp:65536:80"))
+ }
+
+ @Test
+ fun `deserialize rejects guest port above 65535`() {
+ assertNull(PortForwardRule.deserialize("tcp:8080:65536"))
+ }
+
+ @Test
+ fun `deserialize rejects negative port`() {
+ assertNull(PortForwardRule.deserialize("tcp:-1:80"))
+ }
+
+ @Test
+ fun `deserialize allows boundary port 1`() {
+ assertNotNull(PortForwardRule.deserialize("tcp:1:1"))
+ }
+
+ @Test
+ fun `deserialize allows boundary port 65535`() {
+ assertNotNull(PortForwardRule.deserialize("tcp:65535:65535"))
+ }
+
+ @Test
+ fun `deserialize rejects malformed string with wrong part count`() {
+ assertNull(PortForwardRule.deserialize("tcp:8080"))
+ assertNull(PortForwardRule.deserialize("tcp:8080:80:extra"))
+ }
+
+ // ------------------------------------------------------------------
+ // Bug 5 — (hostPort, protocol) dedup helper
+ // ------------------------------------------------------------------
+
+ @Test
+ fun `deduplicateByKey removes existing entry with same hostPort and protocol`() {
+ val existing = setOf(
+ PortForwardRule(8080, 80, "tcp").serialize(),
+ PortForwardRule(9922, 22, "tcp").serialize(),
+ )
+ val newRule = PortForwardRule(8080, 443, "tcp")
+ val result = deduplicatePortForwards(existing, newRule)
+ // Old tcp:8080:80 gone; new tcp:8080:443 present; 9922 untouched.
+ assertEquals(2, result.size)
+ assert(newRule.serialize() in result) { "new rule should be in result" }
+ assert(PortForwardRule(9922, 22, "tcp").serialize() in result) { "unrelated rule should remain" }
+ assert(PortForwardRule(8080, 80, "tcp").serialize() !in result) { "old rule should be removed" }
+ }
+
+ @Test
+ fun `deduplicateByKey keeps different protocol on same host port`() {
+ val existing = setOf(
+ PortForwardRule(8080, 80, "tcp").serialize(),
+ )
+ val newRule = PortForwardRule(8080, 80, "udp")
+ val result = deduplicatePortForwards(existing, newRule)
+ assertEquals(2, result.size)
+ assert(PortForwardRule(8080, 80, "tcp").serialize() in result)
+ assert(newRule.serialize() in result)
+ }
+
+ @Test
+ fun `deduplicateByKey adds new rule when no conflict`() {
+ val existing = setOf(
+ PortForwardRule(9922, 22, "tcp").serialize(),
+ )
+ val newRule = PortForwardRule(8080, 80, "tcp")
+ val result = deduplicatePortForwards(existing, newRule)
+ assertEquals(2, result.size)
+ }
+
+ @Test
+ fun `deduplicateByKey handles empty set`() {
+ val newRule = PortForwardRule(8080, 80, "tcp")
+ val result = deduplicatePortForwards(emptySet<String>(), newRule)
+ assertEquals(setOf(newRule.serialize()), result)
+ }
+}
diff --git a/app/src/test/java/com/excp/podroid/data/repository/UpdateRepositoryTest.kt b/app/src/test/java/com/excp/podroid/data/repository/UpdateRepositoryTest.kt
new file mode 100644
index 0000000..8858f53
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/data/repository/UpdateRepositoryTest.kt
@@ -0,0 +1,123 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ *
+ * Unit tests for pure logic extracted from UpdateRepository.
+ */
+package com.excp.podroid.data.repository
+
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Tests for shouldCheck and isNewer — both are pure functions that can be
+ * exercised without Android context or DataStore.
+ */
+class UpdateRepositoryTest {
+
+ // ------------------------------------------------------------------
+ // shouldCheck (Bug 1: cache clock uses currentTimeMillis, not uptimeMillis)
+ // ------------------------------------------------------------------
+
+ @Test
+ fun `shouldCheck returns true when cache is older than validity window`() {
+ val validity = 24 * 60 * 60 * 1000L
+ val lastCheck = 1_000_000L
+ val now = lastCheck + validity + 1L
+ assertTrue(shouldCheck(now, lastCheck, validity))
+ }
+
+ @Test
+ fun `shouldCheck returns false when cache is within validity window`() {
+ val validity = 24 * 60 * 60 * 1000L
+ val lastCheck = 1_000_000L
+ val now = lastCheck + validity - 1L
+ assertFalse(shouldCheck(now, lastCheck, validity))
+ }
+
+ @Test
+ fun `shouldCheck treats a negative delta as stale (reboot case)`() {
+ // After reboot, now (small uptimeMillis) minus a large pre-shutdown
+ // currentTimeMillis would give a huge negative number with the old
+ // SystemClock.uptimeMillis() approach. With currentTimeMillis the
+ // negative case still represents a clock going backwards: treat as stale.
+ val validity = 24 * 60 * 60 * 1000L
+ val lastCheck = 9_999_999L
+ val now = 1L // simulates a clock that was reset or went backwards
+ assertTrue(shouldCheck(now, lastCheck, validity))
+ }
+
+ @Test
+ fun `shouldCheck returns true when lastCheck is zero and now exceeds validity`() {
+ val validity = 24 * 60 * 60 * 1000L
+ // 0 = never checked; now is more than 24h past epoch, so check is due.
+ assertTrue(shouldCheck(validity + 1L, 0L, validity))
+ }
+
+ // ------------------------------------------------------------------
+ // isNewer (Bug 6: prerelease suffix numeric comparison)
+ // ------------------------------------------------------------------
+
+ @Test
+ fun `isNewer rc10 greater than rc9 (numeric suffix comparison)`() {
+ assertTrue(isNewer("1.2.0-rc10", "1.2.0-rc9"))
+ }
+
+ @Test
+ fun `isNewer rc9 not greater than rc10`() {
+ assertFalse(isNewer("1.2.0-rc9", "1.2.0-rc10"))
+ }
+
+ @Test
+ fun `isNewer release greater than prerelease with same numeric core`() {
+ assertTrue(isNewer("1.2.0", "1.2.0-rc1"))
+ }
+
+ @Test
+ fun `isNewer prerelease not greater than release`() {
+ assertFalse(isNewer("1.2.0-rc1", "1.2.0"))
+ }
+
+ @Test
+ fun `isNewer higher patch version is newer`() {
+ assertTrue(isNewer("1.2.1", "1.2.0"))
+ }
+
+ @Test
+ fun `isNewer same version is not newer`() {
+ assertFalse(isNewer("1.2.0", "1.2.0"))
+ }
+
+ @Test
+ fun `isNewer higher minor version is newer`() {
+ assertTrue(isNewer("1.3.0", "1.2.9"))
+ }
+
+ @Test
+ fun `isNewer higher major version is newer`() {
+ assertTrue(isNewer("2.0.0", "1.9.9"))
+ }
+
+ @Test
+ fun `isNewer lower version is not newer`() {
+ assertFalse(isNewer("1.2.0", "1.2.1"))
+ }
+
+ @Test
+ fun `isNewer rc2 greater than rc1`() {
+ assertTrue(isNewer("1.2.0-rc2", "1.2.0-rc1"))
+ }
+
+ @Test
+ fun `isNewer same prerelease is not newer`() {
+ assertFalse(isNewer("1.2.0-rc1", "1.2.0-rc1"))
+ }
+
+ @Test
+ fun `isNewer handles an overflowing numeric prerelease chunk without crashing`() {
+ // A >18-digit chunk would overflow String.toLong(); must not throw.
+ assertFalse(isNewer("1.2.0-rc1", "1.2.0-rc99999999999999999999"))
+ assertTrue(isNewer("1.2.0-rc99999999999999999999", "1.2.0-rc1"))
+ }
+}