apps: show stale data instead of blank screens when the backend is down
- Commit
e63277baa69a740aebd9a24d000cfdb458c0f104- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 12:13 UTC (14 days ago)
- Parents
eab429c
A relay or backend outage looked identical to 'nothing to show'. FindFamily now exposes the live-connection state in the UI: an offline chip with 'last updated' age, so a dead relay no longer looks like family members being offline. Maps transit no longer blanks the departures board on failure - it serves last-good departures under a stale banner, and a real unavailable state with retry when nothing was ever fetched. MADeveloper persists last-good repos/tests/ issues/PRs/catalog JSON to disk (atomic writes) and renders it marked stale when live reads fail, each endpoint settling independently. Verified: findfamily and madeveloper suites pass; maps transit tests pass (one pre-existing unrelated location-sensor failure in the full maps suite, fails standalone too).
Diff
findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.ktindex f9a88ff38f..4d8517315c 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/network/Networking.kt@@ -21,6 +21,9 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex@@ -305,6 +308,19 @@ object Networking { /** True while the live socket is connected. */ val liveConnected: Boolean get() = wsSession != null + private val _liveConnectedFlow = MutableStateFlow(false)++ /**+ * Observable form of [liveConnected] for the UI: false means the relay is+ * unreachable, so family positions on screen may be stale rather than+ * current. Updated only where [wsSession] is assigned/cleared.+ */+ val liveConnectedFlow: StateFlow<Boolean> = _liveConnectedFlow.asStateFlow()++ internal fun setLiveConnected(connected: Boolean) {+ _liveConnectedFlow.value = connected+ }+ internal data class KeyResult(val status: Int, val bundle: ByteArray?) /** Reads 8 big-endian bytes at [off] back into the original Long bit pattern. */@@ -354,6 +370,7 @@ object Networking { runCatching { webSocket(WS_URL) { wsSession = this+ setLiveConnected(true) sendSubscribe() backoff = BACKOFF_INITIAL_MS superviseConnection(connScope, outerScope, onLocations, onUwb, onRawMsg)@@ -361,6 +378,7 @@ object Networking { }.onFailure { Log.status(TAG, "live WS loop error", it) } connScope.cancel() wsSession = null+ setLiveConnected(false) // Fail any awaiting key lookups so their callers don't hang until timeout. pendingKeyRequests.values.forEach { it.complete(null) } pendingKeyRequests.clear()@@ -376,7 +394,7 @@ object Networking { @Synchronized fun stopLive() {- liveJob?.cancel(); liveJob = null; wsSession = null+ liveJob?.cancel(); liveJob = null; wsSession = null; setLiveConnected(false) pendingKeyRequests.values.forEach { it.complete(null) } pendingKeyRequests.clear() pendingResolves.values.forEach { it.complete(null) }
findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyUiContract.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyUiContract.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyUiContract.ktindex a0df8899d9..b9f40faffc 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyUiContract.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyUiContract.kt@@ -118,6 +118,10 @@ interface PersonActions { data class MainPageUiState( val usingGpsFallback: Boolean = false, val familyList: FamilyListUiState = FamilyListUiState(),+ /** True while the live relay socket is connected; false means positions may be stale. */+ val relayConnected: Boolean = true,+ /** Epoch millis of the newest family location report, for the disconnected staleness line. */+ val lastLocationMillis: Long? = null, ) /**
findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyViewModel.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyViewModel.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyViewModel.ktindex 82375141f5..47f1c06f03 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyViewModel.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/FindFamilyViewModel.kt@@ -89,6 +89,9 @@ class FindFamilyViewModel( val latestLocationByUser: StateFlow<Map<Long, LocationValue>> = repository.latestLocationByUser .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap()) + /** Relay socket connectivity for the top-bar status; false must not read as family offline. */+ val relayConnected: StateFlow<Boolean> = Networking.liveConnectedFlow+ /** Connected people (mutual connection or awaiting our response) — the main list. */ val connectedUsers: StateFlow<List<User>> = repository.users .map { list ->
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.ktindex 688b0b70fc..769c38e089 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPage.kt@@ -202,6 +202,8 @@ fun MainPage( val usersByLocationName by ffViewModel.usersByLocationName.collectAsState() val userPositions by ffViewModel.latestLocationByUser.collectAsState() + val relayConnected by ffViewModel.relayConnected.collectAsState()+ val context = LocalContext.current // The selected contact (from the sheet route on top of the stack),@@ -219,6 +221,10 @@ fun MainPage( val state = MainPageUiState( usingGpsFallback = usingGpsFallback,+ relayConnected = relayConnected,+ // Newest report on screen (reportedAt, not the fix's measurement+ // time) — what "last updated" means when the relay drops.+ lastLocationMillis = userPositions.values.maxOfOrNull { it.reportedAt.toEpochMilliseconds() }, familyList = FamilyListUiState( connectedUsers = connectedUsers, awaitingRequestUsers = awaitingRequestUsers,
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageContent.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageContent.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageContent.ktindex b4b109cd56..c7c1f66c23 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageContent.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageContent.kt@@ -8,6 +8,7 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding import com.vayunmathur.library.ui.BottomSheetDefaults import com.vayunmathur.library.ui.BottomSheetScaffold import com.vayunmathur.library.ui.ExperimentalMaterial3Api@@ -90,7 +91,16 @@ fun MainPageContent( if (expanded) { FindFamilyWideLayout(- map = { map() },+ map = {+ Box(Modifier.fillMaxSize()) {+ map()+ RelayStatusChip(+ relayConnected = state.relayConnected,+ lastLocationMillis = state.lastLocationMillis,+ modifier = Modifier.align(Alignment.TopStart).padding(16.dp),+ )+ }+ }, panel = { modifier -> // Always the family list: person/waypoint sheets are // separate destinations over the map, on every form factor.
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageOverlays.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageOverlays.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageOverlays.ktindex d21e484119..b9a909d647 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageOverlays.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MainPageOverlays.kt@@ -71,6 +71,11 @@ internal fun MapOverlayBar( TopAppBarOverlay( onNavigateBack = null, actions = overlayActions,- title = null+ title = {+ RelayStatusChip(+ relayConnected = state.relayConnected,+ lastLocationMillis = state.lastLocationMillis,+ )+ } ) }
findfamily/src/main/java/com/vayunmathur/findfamily/ui/RelayStatusChip.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/RelayStatusChip.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/RelayStatusChip.ktnew file mode 100644index 0000000000..cb7770d37c--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/RelayStatusChip.kt@@ -0,0 +1,89 @@+package com.vayunmathur.findfamily.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.findfamily.R+import com.vayunmathur.library.ui.IconWifiFull+import com.vayunmathur.library.ui.IconWifiOff+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import kotlin.time.Instant+import kotlinx.coroutines.delay++/**+ * Relay connectivity for the map top bar.+ *+ * A relay outage and every family member being offline used to look the+ * same: pins simply stopped moving. This chip makes the relay itself+ * visible — connected quietly, disconnected with the age of the newest+ * location on screen so stale positions are never read as current.+ */+@Composable+fun RelayStatusChip(relayConnected: Boolean, lastLocationMillis: Long?, modifier: Modifier = Modifier) {+ val context = LocalContext.current+ // Re-render the "last updated" age while disconnected; it is the whole+ // point of the disconnected state and must not freeze at disconnect time.+ var nowMillis by remember { mutableLongStateOf(System.currentTimeMillis()) }+ LaunchedEffect(relayConnected) {+ while (!relayConnected) {+ nowMillis = System.currentTimeMillis()+ delay(30_000L)+ }+ }+ val container = if (relayConnected) {+ MaterialTheme.colorScheme.surfaceContainerHigh+ } else {+ MaterialTheme.colorScheme.errorContainer+ }+ val content = if (relayConnected) {+ MaterialTheme.colorScheme.onSurface+ } else {+ MaterialTheme.colorScheme.onErrorContainer+ }+ val label = if (relayConnected) {+ stringResource(R.string.relay_connected)+ } else if (lastLocationMillis != null) {+ stringResource(+ R.string.relay_disconnected_last_updated,+ timestring(Instant.fromEpochMilliseconds(lastLocationMillis), context),+ )+ } else {+ stringResource(R.string.relay_disconnected_no_locations)+ }+ Row(+ modifier = modifier+ .background(container, RoundedCornerShape(50))+ .padding(horizontal = 10.dp, vertical = 6.dp),+ horizontalArrangement = Arrangement.spacedBy(6.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ if (relayConnected) {+ IconWifiFull(Modifier.size(16.dp), tint = content)+ } else {+ IconWifiOff(Modifier.size(16.dp), tint = content)+ }+ Text(+ label,+ style = MaterialTheme.typography.labelMedium,+ color = content,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+}
findfamily/src/main/res/values/strings.xml
diff --git a/findfamily/src/main/res/values/strings.xml b/findfamily/src/main/res/values/strings.xmlindex f6e7485d5a..2a5ec3d39b 100644--- a/findfamily/src/main/res/values/strings.xml+++ b/findfamily/src/main/res/values/strings.xml@@ -121,6 +121,13 @@ <!-- MainPage: BatteryBar percentage label. %1$d = battery level 0-100, e.g. 85 --> <string name="battery_percentage"><xliff:g id="battery_level" example="85">%1$d</xliff:g>%%</string> + <!-- MainPage: relay status chip while the live socket is connected. Short label -->+ <string name="relay_connected">Relay connected</string>+ <!-- MainPage: relay status chip while disconnected. %1$s = age of newest location, e.g. 5 minutes ago -->+ <string name="relay_disconnected_last_updated">Relay offline · Last updated <xliff:g id="last_updated" example="5 minutes ago">%1$s</xliff:g></string>+ <!-- MainPage: relay status chip while disconnected with no location received yet -->+ <string name="relay_disconnected_no_locations">Relay offline · Locations may be out of date</string>+ <!-- MainPage: timestring helper for just now. Adverbial phrase, past --> <string name="time_just_now">just now</string> <!-- MainPage: timestring past minutes. %1$d = count, e.g. 5 -->
madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.ktindex 6705c24cdb..e4de4c956c 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt@@ -15,6 +15,9 @@ import com.vayunmathur.madeveloper.domain.TestsStatus import com.vayunmathur.madeveloper.domain.TreeEntry import java.net.URLEncoder +/** A parsed payload plus provenance: [stale] means it came from the last-good disk cache. */+data class LastGoodResult<T>(val value: T, val stale: Boolean, val fetchedAtMillis: Long?)+ /** * Reads the maproj git host through [NetworkClient] (FIRST_PARTY trust is * set once by the activity). Repositories, branches, commits, trees and@@ -28,12 +31,38 @@ class GitHostRepository( // through NetworkClient (below); tests substitute canned host replies so // the parsing, caching and error behaviour above it run off-device. private val fetcher: suspend (String) -> String = { url -> fetchViaNetwork(url) },+ // Disk last-good store for the outage path; null in tests that do not+ // exercise it. The in-memory tree/file caches below stay as-is.+ private val lastGood: LastGoodStore? = null, ) { private var treeCache: Map<String, List<TreeEntry>> = emptyMap() private var fileCache: Map<String, GitFile> = emptyMap() + /**+ * Fetch [url] live, persisting the raw JSON under [key]; on any failure+ * serve the persisted last-good instead. Rethrows when no last-good+ * exists, so first-run outages still surface as errors.+ */+ private suspend fun <T> fetchLastGood(key: String, url: String, parse: (String) -> T): LastGoodResult<T> {+ return try {+ val text = fetchText(url)+ val now = System.currentTimeMillis()+ lastGood?.write(key, text, now)+ LastGoodResult(withContext(Dispatchers.IO) { parse(text) }, stale = false, fetchedAtMillis = now)+ } catch (e: kotlinx.coroutines.CancellationException) {+ throw e+ } catch (e: Exception) {+ val cached = lastGood?.read(key) ?: throw e+ LastGoodResult(withContext(Dispatchers.IO) { parse(cached.text) }, stale = true, fetchedAtMillis = cached.fetchedAtMillis)+ }+ }+ /** Repositories from `GET /api/repos`. */- suspend fun repos(): List<GitRepo> = withContext(Dispatchers.IO) { GitParsers.parseRepos(fetchText("$GIT_HOST/api/repos")) }+ suspend fun repos(): List<GitRepo> = reposResult().value++ /** Repositories with last-good provenance, for the stale indicator. */+ suspend fun reposResult(): LastGoodResult<List<GitRepo>> =+ fetchLastGood("repos", "$GIT_HOST/api/repos", GitParsers::parseRepos) /** Branches and recent commits from `GET /api/repos/<repo>`. */ suspend fun repo(name: String): RepoDetail = withContext(Dispatchers.IO) {@@ -50,18 +79,34 @@ class GitHostRepository( } /** CI status from `/tests.json`. */- suspend fun tests(): TestsStatus = withContext(Dispatchers.IO) { fetchText("$GIT_HOST/tests.json").let(GitParsers::parseTests) }+ suspend fun tests(): TestsStatus = testsResult().value++ /** CI status with last-good provenance, for the stale indicator. */+ suspend fun testsResult(): LastGoodResult<TestsStatus> =+ fetchLastGood("tests", "$GIT_HOST/tests.json", GitParsers::parseTests) /** Open issues from `/issues.json?view=open`. */- suspend fun issues(): List<GitIssue> = withContext(Dispatchers.IO) { GitParsers.parseIssues(fetchText("$GIT_HOST/issues.json?view=open")) }+ suspend fun issues(): List<GitIssue> = issuesResult().value++ /** Open issues with last-good provenance, for the stale indicator. */+ suspend fun issuesResult(): LastGoodResult<List<GitIssue>> =+ fetchLastGood("issues", "$GIT_HOST/issues.json?view=open", GitParsers::parseIssues) /** Open pull requests from `/prs.json`. */- suspend fun prs(): List<GitPr> = withContext(Dispatchers.IO) { GitParsers.parsePrs(fetchText("$GIT_HOST/prs.json")) }+ suspend fun prs(): List<GitPr> = prsResult().value++ /** Open pull requests with last-good provenance, for the stale indicator. */+ suspend fun prsResult(): LastGoodResult<List<GitPr>> =+ fetchLastGood("prs", "$GIT_HOST/prs.json", GitParsers::parsePrs) /** Available builds from the first-party F-Droid repo (read-only catalog). */- suspend fun catalog(): List<CatalogApp> = withContext(Dispatchers.IO) {- GitParsers.parseFdroidIndex(fetchText("$FDROID_BASE/index-v2.json"), FDROID_BASE)- }+ suspend fun catalog(): List<CatalogApp> = catalogResult().value++ /** Catalog with last-good provenance, for the stale indicator. */+ suspend fun catalogResult(): LastGoodResult<List<CatalogApp>> = fetchLastGood(+ "catalog",+ "$FDROID_BASE/index-v2.json",+ ) { text -> GitParsers.parseFdroidIndex(text, FDROID_BASE) } /** Tree of [path] in [repo] on [branch]; cached per repo+branch+path. */ suspend fun tree(repo: String, branch: String, path: String): List<TreeEntry> {
madeveloper/src/main/java/com/vayunmathur/madeveloper/data/LastGoodStore.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/LastGoodStore.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/LastGoodStore.ktnew file mode 100644index 0000000000..f212e92ceb--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/LastGoodStore.kt@@ -0,0 +1,43 @@+package com.vayunmathur.madeveloper.data++import java.io.File++/** One persisted last-good payload: raw JSON plus when it was fetched. */+data class LastGoodEntry(val text: String, val fetchedAtMillis: Long)++/**+ * Disk persistence for last-good host JSON, so a backend outage renders the+ * previous data (marked stale) instead of blanking the app.+ *+ * Keys are short stable names (`repos`, `tests`, …), never URLs, so a host+ * rename does not orphan the cache. Implementations must never throw into+ * the caller: a broken cache is just a cache miss.+ */+interface LastGoodStore {+ fun read(key: String): LastGoodEntry?+ fun write(key: String, text: String, fetchedAtMillis: Long)+}++/**+ * [LastGoodStore] over plain files in [dir]: `<key>.json` for the payload and+ * `<key>.meta` for the fetch time. Writing via a temp file + rename keeps a+ * crash mid-write from leaving a truncated payload behind.+ */+class FileLastGoodStore(private val dir: File) : LastGoodStore {+ override fun read(key: String): LastGoodEntry? = runCatching {+ val json = File(dir, "$key.json")+ if (!json.isFile) return null+ val at = File(dir, "$key.meta").readText().trim().toLongOrNull() ?: return null+ LastGoodEntry(json.readText(), at)+ }.getOrNull()++ override fun write(key: String, text: String, fetchedAtMillis: Long) {+ runCatching {+ dir.mkdirs()+ val tmp = File(dir, "$key.json.tmp")+ tmp.writeText(text)+ tmp.renameTo(File(dir, "$key.json"))+ File(dir, "$key.meta").writeText(fetchedAtMillis.toString())+ }+ }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.ktindex e58c59c1ea..4b189c7608 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt@@ -62,6 +62,10 @@ data class MaDevUiState( /** Registered but the server has not approved this device yet (socket refused 403). */ val awaitingApproval: Boolean = false, val pending: List<PendingInstall> = emptyList(),+ /** True when the git/catalog data on screen is last-good, not a live fetch. */+ val stale: Boolean = false,+ /** When the stale data was fetched, if known. */+ val staleAtMillis: Long? = null, ) /** Holds Developer state: git pages, catalog, push socket and installs. */@@ -70,7 +74,14 @@ class MaDevViewModel(app: Application) : AndroidViewModel(app) { // the push socket is opened, and how a pushed APK's bytes are fetched. // They exist so the state machine below can run off-device; the app // itself always takes the defaults.- internal var repo: GitHostRepository = GitHostRepository()+ internal var repo: GitHostRepository = GitHostRepository(+ lastGood = com.vayunmathur.madeveloper.data.FileLastGoodStore(+ File(app.filesDir, "git_host_last_good")+ ),+ )++ /** Fetch time of the newest live data shown, for labelling kept/stale data. */+ private var lastLiveFetchMillis: Long? = null internal var transportFactory: suspend (String, String?) -> DevSocketTransport = { url, token -> WebSocketDevTransport.connect(url, token) } internal var deviceRegistrar: suspend (String) -> DevRegistration =@@ -112,21 +123,49 @@ class MaDevViewModel(app: Application) : AndroidViewModel(app) { fun refresh() { state = state.copy(loading = true, error = null) viewModelScope.launch {- try {- // All four host fetches run concurrently; any IOException- // cancels the rest and lands in the same error state.- coroutineScope {- val repos = async { repo.repos() }- val tests = async { repo.tests() }- val issues = async { repo.issues() }- val prs = async { repo.prs() }- state = state.copy(- loading = false, repos = repos.await(), tests = tests.await(),- issues = issues.await(), prs = prs.await(),- )- }- } catch (e: java.io.IOException) {- state = state.copy(loading = false, error = getApplication<Application>().friendlyError(e))+ // Each fetch settles independently: one failing endpoint must not+ // blank the others, and a failure with last-good (disk, or data+ // already on screen) serves that instead of emptying the app.+ coroutineScope {+ val repos = async { runCatching { repo.reposResult() } }+ val tests = async { runCatching { repo.testsResult() } }+ val issues = async { runCatching { repo.issuesResult() } }+ val prs = async { runCatching { repo.prsResult() } }+ val reposR = repos.await()+ val testsR = tests.await()+ val issuesR = issues.await()+ val prsR = prs.await()+ val results = listOf(reposR, testsR, issuesR, prsR)+ val anyStale = results.any { it.getOrNull()?.stale == true } ||+ (reposR.isFailure && state.repos.isNotEmpty()) ||+ (testsR.isFailure && state.tests != null) ||+ (issuesR.isFailure && state.issues.isNotEmpty()) ||+ (prsR.isFailure && state.prs.isNotEmpty())+ val staleAt = results.mapNotNull { it.getOrNull() }+ .filter { it.stale }.mapNotNull { it.fetchedAtMillis }.maxOrNull()+ ?: if (anyStale) lastLiveFetchMillis else null+ results.mapNotNull { it.getOrNull() }.filter { !it.stale }+ .mapNotNull { it.fetchedAtMillis }.maxOrNull()+ ?.let { lastLiveFetchMillis = it }+ state = state.copy(+ loading = false,+ repos = reposR.getOrNull()?.value ?: state.repos,+ tests = testsR.getOrNull()?.value ?: state.tests,+ issues = issuesR.getOrNull()?.value ?: state.issues,+ prs = prsR.getOrNull()?.value ?: state.prs,+ stale = anyStale,+ staleAtMillis = if (anyStale) staleAt else null,+ // An error only when there is nothing (live, stale or+ // already on screen) to show for the headline fetch.+ error = if (reposR.isFailure && state.repos.isEmpty()) {+ getApplication<Application>().friendlyError(+ reposR.exceptionOrNull() as? java.io.IOException+ ?: java.io.IOException(reposR.exceptionOrNull()?.message)+ )+ } else {+ null+ },+ ) } } }@@ -135,8 +174,22 @@ class MaDevViewModel(app: Application) : AndroidViewModel(app) { fun loadCatalog() { if (state.catalog.isNotEmpty()) return viewModelScope.launch {- try { state = state.copy(catalog = repo.catalog()) }- catch (e: java.io.IOException) { state = state.copy(error = getApplication<Application>().friendlyError(e)) }+ runCatching { repo.catalogResult() }+ .onSuccess { result ->+ if (!result.stale) result.fetchedAtMillis?.let { lastLiveFetchMillis = it }+ state = state.copy(+ catalog = result.value,+ stale = state.stale || result.stale,+ staleAtMillis = if (result.stale) result.fetchedAtMillis else state.staleAtMillis,+ )+ }+ .onFailure { e ->+ state = if (state.catalog.isEmpty()) {+ state.copy(error = getApplication<Application>().friendlyError(e))+ } else {+ state.copy(stale = true, staleAtMillis = state.staleAtMillis ?: lastLiveFetchMillis)+ }+ } } }
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CatalogScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CatalogScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CatalogScreen.ktindex a510fb2bb7..a5e34ca681 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CatalogScreen.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/CatalogScreen.kt@@ -30,6 +30,7 @@ fun CatalogScreen(state: MaDevUiState, onBack: () -> Unit) { Modifier.fillMaxSize().padding(padding), verticalArrangement = Arrangement.spacedBy(Spacing.md), ) {+ item { StaleBanner(state) } item { DashboardSection( title = "About this catalog",
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/HomeScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/HomeScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/HomeScreen.ktindex 4ed914376b..5a47654131 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/HomeScreen.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/HomeScreen.kt@@ -68,6 +68,7 @@ fun HomeScreen( Modifier.fillMaxSize().padding(padding), verticalArrangement = Arrangement.spacedBy(Spacing.md), ) {+ item { StaleBanner(state) } item { PushStatusSection(state, onOpenPush) } state.tests?.latest?.let { latest -> item {
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/IssuesScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/IssuesScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/IssuesScreen.ktindex ae68de6fd4..b6b6468d6e 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/IssuesScreen.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/IssuesScreen.kt@@ -36,6 +36,7 @@ fun IssuesScreen(state: MaDevUiState, onOpenIssue: (GitIssue) -> Unit, onBack: ( Modifier.fillMaxSize().padding(padding), verticalArrangement = Arrangement.spacedBy(Spacing.md), ) {+ item { StaleBanner(state) } if (state.issues.isEmpty()) { item { EmptyState(
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/PullRequestsScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/PullRequestsScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/PullRequestsScreen.ktindex 846e27da5c..6ca225bfc0 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/PullRequestsScreen.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/PullRequestsScreen.kt@@ -34,6 +34,7 @@ fun PullRequestsScreen(state: MaDevUiState, onOpenPr: (GitPr) -> Unit, onBack: ( Modifier.fillMaxSize().padding(padding), verticalArrangement = Arrangement.spacedBy(Spacing.md), ) {+ item { StaleBanner(state) } if (state.prs.isEmpty()) { item { EmptyState(
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/StaleBanner.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/StaleBanner.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/StaleBanner.ktnew file mode 100644index 0000000000..595c8dd5a3--- /dev/null+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/StaleBanner.kt@@ -0,0 +1,46 @@+package com.vayunmathur.madeveloper.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import com.vayunmathur.library.ui.IconWarning+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Spacing+import com.vayunmathur.library.ui.Text+import com.vayunmathur.madeveloper.platform.MaDevUiState+import java.text.DateFormat+import java.util.Date++/**+ * Stale-data indication: the screen is showing last-good data because the+ * live fetch failed. Rendered only when [MaDevUiState.stale] is set, so a+ * live screen looks exactly as before.+ */+@Composable+fun StaleBanner(state: MaDevUiState, modifier: Modifier = Modifier) {+ if (!state.stale) return+ val at = state.staleAtMillis?.let {+ DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(it))+ }+ Row(+ modifier = modifier+ .fillMaxWidth()+ .background(MaterialTheme.colorScheme.errorContainer)+ .padding(horizontal = Spacing.lg, vertical = Spacing.sm),+ horizontalArrangement = Arrangement.spacedBy(Spacing.sm),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ IconWarning(tint = MaterialTheme.colorScheme.onErrorContainer)+ Text(+ if (at != null) "Showing saved data from $at — couldn't reach the server"+ else "Showing saved data — couldn't reach the server",+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onErrorContainer,+ )+ }+}
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/TestsScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/TestsScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/TestsScreen.ktindex 19de2b523a..8cb67f77b5 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/TestsScreen.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/TestsScreen.kt@@ -35,6 +35,7 @@ fun TestsScreen(state: MaDevUiState, onBack: () -> Unit) { Modifier.fillMaxSize().padding(padding), verticalArrangement = Arrangement.spacedBy(Spacing.md), ) {+ item { StaleBanner(state) } if (state.tests == null) { item { EmptyState(
madeveloper/src/test/java/com/vayunmathur/madeveloper/GitHostLastGoodTest.kt
diff --git a/madeveloper/src/test/java/com/vayunmathur/madeveloper/GitHostLastGoodTest.kt b/madeveloper/src/test/java/com/vayunmathur/madeveloper/GitHostLastGoodTest.ktnew file mode 100644index 0000000000..c3ec18c852--- /dev/null+++ b/madeveloper/src/test/java/com/vayunmathur/madeveloper/GitHostLastGoodTest.kt@@ -0,0 +1,86 @@+package com.vayunmathur.madeveloper++import com.vayunmathur.madeveloper.data.FileLastGoodStore+import com.vayunmathur.madeveloper.data.GitHostRepository+import com.vayunmathur.madeveloper.data.LastGoodEntry+import com.vayunmathur.madeveloper.data.LastGoodStore+import java.io.File+import java.io.IOException+import java.nio.file.Files+import kotlinx.coroutines.test.runTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Last-good disk serving in [GitHostRepository]: an outage must not blank repos/tests/catalog. */+class GitHostLastGoodTest {++ private class MemoryStore : LastGoodStore {+ val entries = mutableMapOf<String, LastGoodEntry>()+ override fun read(key: String): LastGoodEntry? = entries[key]+ override fun write(key: String, text: String, fetchedAtMillis: Long) {+ entries[key] = LastGoodEntry(text, fetchedAtMillis)+ }+ }++ private val reposJson = """[{"name":"Modern-Apps","defaultBranch":"main","headSha":"aabbccdd11223344","headSubject":"top","headTime":"2026-11-16T10:00:00Z"}]"""+ private val testsJson = """{"latest":{"id":"a","sha":"abc123","subject":"fix","status":"passed","failed":0,"tests":10},"history":[]}"""+ private val catalogJson = """{"packages":{"com.example.app":{"metadata":{"name":{"en-US":"Example"},"summary":{"en-US":"Demo"}},"versions":{"h1":{"file":{"name":"/a_1.apk","size":100},"manifest":{"versionCode":1,"versionName":"1.0"}}}}}}"""++ private fun fetcher(fail: () -> Boolean): suspend (String) -> String = { url ->+ if (fail()) throw IOException("HTTP 503 for $url")+ when {+ url.endsWith("/api/repos") -> reposJson+ url.contains("/tests.json") -> testsJson+ url.contains("index-v2.json") -> catalogJson+ else -> throw IOException("unexpected url: $url")+ }+ }++ @Test+ fun `repos tests and catalog serve last-good from disk on failure`() = runTest {+ var fail = false+ val store = MemoryStore()+ val repo = GitHostRepository(fetcher { fail }, store)+ assertFalse(repo.reposResult().stale)+ assertFalse(repo.testsResult().stale)+ assertFalse(repo.catalogResult().stale)+ assertEquals(setOf("repos", "tests", "catalog"), store.entries.keys)++ fail = true+ val repos = repo.reposResult()+ assertTrue(repos.stale)+ assertEquals("Modern-Apps", repos.value.single().name)+ assertTrue(repo.testsResult().stale)+ assertEquals("passed", repo.testsResult().value.latest?.status)+ val catalog = repo.catalogResult()+ assertTrue(catalog.stale)+ assertEquals("Example", catalog.value.single().name)+ // The plain APIs serve the same last-good values, not empty.+ assertEquals(1, repo.repos().size)+ assertEquals(1, repo.catalog().size)+ }++ @Test+ fun `failure with no last-good still throws`() = runTest {+ val repo = GitHostRepository(fetcher { true }, MemoryStore())+ assertFailsWith<IOException> { repo.reposResult() }+ assertFailsWith<IOException> { repo.catalogResult() }+ }++ @Test+ fun `file store round-trips payload and fetch time`() {+ val dir = Files.createTempDirectory("lastgood").toFile()+ try {+ val store = FileLastGoodStore(dir)+ store.write("repos", reposJson, 1234L)+ assertEquals(LastGoodEntry(reposJson, 1234L), store.read("repos"))+ assertEquals(null, store.read("missing"))+ assertTrue(File(dir, "repos.json").isFile)+ } finally {+ dir.deleteRecursively()+ }+ }+}
maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.ktindex 85740e0940..23cf9aa77d 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt@@ -33,6 +33,20 @@ import java.time.OffsetDateTime * and cannot be exercised at compile time; the endpoint/parse below is * verified by shape only. */+/**+ * A departure board plus its provenance.+ *+ * [stale] means [departures] are the last-good board served because the live+ * fetch failed; [unavailable] means the fetch failed and no last-good board+ * exists. [fetchedAtMillis] is when [departures] were actually fetched.+ */+data class DeparturesResult(+ val departures: List<Departure>,+ val stale: Boolean,+ val unavailable: Boolean,+ val fetchedAtMillis: Long?,+)+ object TransitousDataSource { private const val BASE_URL = "https://api.maproj.org/api/transit"@@ -55,21 +69,29 @@ object TransitousDataSource { "User-Agent" to "Modern-Apps-Maps/1.0", ) - /**- * A cached fetch. [ok] separates "successfully fetched, genuinely empty"- * from "the fetch failed", so only the latter expires quickly.- */- private class Cached<T>(val value: T, val ok: Boolean) {+ /** A successful fetch; failures never overwrite it, so it doubles as last-good. */+ private class Cached<T>(val value: T) { val at: Long = System.currentTimeMillis()- fun isFresh(okTtlMs: Long): Boolean =- System.currentTimeMillis() - at < if (ok) okTtlMs else FAILURE_TTL_MS+ fun isFresh(ttlMs: Long): Boolean = System.currentTimeMillis() - at < ttlMs } - // Departures cache keyed on stop id, with a short TTL (live data).+ // Last-good departures keyed on stop id, with a short freshness TTL (live data). private val departuresCache = object : LinkedHashMap<String, Cached<List<Departure>>>(16, 0.75f, true) { override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Cached<List<Departure>>>) = size > 32 } + /** When each stop last failed, so failures expire after [FAILURE_TTL_MS] without erasing last-good. */+ private val failureAt = object : LinkedHashMap<String, Long>(16, 0.75f, true) {+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Long>) = size > 32+ }++ private fun lastGood(stopId: String): Cached<List<Departure>>? =+ synchronized(departuresCache) { departuresCache[stopId] }++ private fun staleResult(stopId: String): DeparturesResult? = lastGood(stopId)?.let {+ DeparturesResult(it.value, stale = true, unavailable = false, fetchedAtMillis = it.at)+ }+ /** * Test seam: fetch the raw board DTO for [stopId] (null on any failure). * Defaults to the live network; tests replace it with canned wire payloads@@ -88,20 +110,47 @@ object TransitousDataSource { * [DEPARTURES_TTL_MS] on success and only [FAILURE_TTL_MS] on failure; pass * [force] (a manual refresh) to bypass the cache. */- suspend fun departures(stopId: String, force: Boolean = false): List<Departure> {+ suspend fun departures(stopId: String, force: Boolean = false): List<Departure> =+ departuresResult(stopId, force).departures++ /**+ * Live departures plus provenance for [stopId]. Never throws.+ *+ * On failure the last-good board is served with [DeparturesResult.stale]+ * instead of blanking; only when no fetch has ever succeeded for the stop+ * is the result [DeparturesResult.unavailable]. A genuinely empty+ * successful board is neither stale nor unavailable.+ */+ suspend fun departuresResult(stopId: String, force: Boolean = false): DeparturesResult { if (!force) {- synchronized(departuresCache) {- departuresCache[stopId]?.let { if (it.isFresh(DEPARTURES_TTL_MS)) return it.value }+ lastGood(stopId)?.let {+ if (it.isFresh(DEPARTURES_TTL_MS)) {+ return DeparturesResult(it.value, stale = false, unavailable = false, fetchedAtMillis = it.at)+ }+ }+ val failedAt = synchronized(failureAt) { failureAt[stopId] }+ if (failedAt != null && System.currentTimeMillis() - failedAt < FAILURE_TTL_MS) {+ return staleResult(stopId)+ ?: DeparturesResult(emptyList(), stale = false, unavailable = true, fetchedAtMillis = null) } }- val fetched = runCatching {- fetchStoptimes(stopId)?.stopTimes?.mapNotNull { it.toDeparture() }.orEmpty()- }- val deps = fetched.getOrDefault(emptyList())- synchronized(departuresCache) { departuresCache[stopId] = Cached(deps, fetched.isSuccess) }- return deps+ val dto = runCatching { fetchStoptimes(stopId) }.getOrNull()+ ?: run {+ synchronized(failureAt) { failureAt[stopId] = System.currentTimeMillis() }+ return staleResult(stopId)+ ?: DeparturesResult(emptyList(), stale = false, unavailable = true, fetchedAtMillis = null)+ }+ val deps = dto.stopTimes.mapNotNull { it.toDeparture() }+ val cached = Cached(deps)+ synchronized(departuresCache) { departuresCache[stopId] = cached }+ synchronized(failureAt) { failureAt.remove(stopId) }+ return DeparturesResult(deps, stale = false, unavailable = false, fetchedAtMillis = cached.at) } + /** Last-good board without fetching, or unavailable when none exists. For known-offline callers. */+ fun cachedResult(stopId: String): DeparturesResult = staleResult(stopId)+ ?: DeparturesResult(emptyList(), stale = false, unavailable = true, fetchedAtMillis = null)+ private suspend fun fetchDepartures(stopId: String): List<Departure> = withContext(Dispatchers.IO) { // Proxied via self-hosted (same object-singleton shape as the retired Google fetchers): // server forwards to api.transitous.org/api/v1/stoptimes with a short cache.
maps/src/main/java/com/vayunmathur/maps/platform/TransitStopsViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/platform/TransitStopsViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/platform/TransitStopsViewModel.ktindex a586968009..257255c80b 100644--- a/maps/src/main/java/com/vayunmathur/maps/platform/TransitStopsViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/platform/TransitStopsViewModel.kt@@ -105,14 +105,33 @@ class TransitStopsViewModel(application: Application) : AndroidViewModel(applica .distinctBy { it.line to it.scheduledMillis } .sortedBy { it.realtimeMillis } }.getOrDefault(emptyList())- val deps = offline.ifEmpty {- if (ConnectivityMonitor.isOnline(getApplication())) {- TransitousDataSource.departures(stop.id, force = force)- } else {- emptyList()- }+ if (offline.isNotEmpty()) {+ emit(DeparturesState.Loaded(stop, offline))+ } else if (ConnectivityMonitor.isOnline(getApplication())) {+ val result = TransitousDataSource.departuresResult(stop.id, force = force)+ emit(+ DeparturesState.Loaded(+ stop,+ result.departures,+ stale = result.stale,+ unavailable = result.unavailable,+ fetchedAtMillis = result.fetchedAtMillis,+ )+ )+ } else {+ // No pack schedule and no connectivity: serve any+ // last-good board from this session, else unavailable.+ val result = TransitousDataSource.cachedResult(stop.id)+ emit(+ DeparturesState.Loaded(+ stop,+ result.departures,+ stale = result.stale,+ unavailable = result.unavailable,+ fetchedAtMillis = result.fetchedAtMillis,+ )+ ) }- emit(DeparturesState.Loaded(stop, deps)) }.flowOn(Dispatchers.IO) } }@@ -242,6 +261,20 @@ sealed interface DeparturesState { data object Idle : DeparturesState /** Immutable value describing loading; carries stop. */ data class Loading(val stop: TransitStop) : DeparturesState- /** Immutable value describing loaded; carries stop, departures. */- data class Loaded(val stop: TransitStop, val departures: List<Departure>) : DeparturesState++ /**+ * Immutable value describing loaded; carries stop, departures.+ *+ * [stale] means the live fetch failed and [departures] are last-good;+ * [unavailable] means it failed with no last-good to serve. Neither is+ * set for a genuinely empty successful board. [fetchedAtMillis] is when+ * [departures] were fetched (the last-good time when [stale]).+ */+ data class Loaded(+ val stop: TransitStop,+ val departures: List<Departure>,+ val stale: Boolean = false,+ val unavailable: Boolean = false,+ val fetchedAtMillis: Long? = null,+ ) : DeparturesState }
maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.ktindex 722cb3a6bd..87b58ba85d 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt@@ -33,6 +33,7 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.ErrorState import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.LoadingState import com.vayunmathur.library.ui.IconButton@@ -65,8 +66,9 @@ private val BoardStatusHeight = 160.dp * shared [ModalBottomSheet] from `:library:ui` (no raw scaffold), mirroring * [ParkingSheet] / [LayersSheet]. *- * The board is ONLINE-ONLY (Transitous); a failed fetch degrades to the- * "no departures" state rather than an error.+ * The live overlay is ONLINE-ONLY (Transitous); a failed fetch serves the+ * last-good board with a stale indication, or an unavailable state with+ * retry when no last-good board exists — never a silent blank. */ @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -137,13 +139,25 @@ fun DeparturesSheet( ) DeparturesState.Idle -> Unit is DeparturesState.Loaded -> {- if (state.departures.isEmpty()) {- EmptyState(- title = stringResource(R.string.transit_departures_none),+ when {+ state.unavailable -> ErrorState(+ title = stringResource(R.string.transit_departures_unavailable_title),+ message = stringResource(R.string.transit_departures_unavailable_message),+ retryLabel = stringResource(R.string.transit_departures_retry),+ onRetry = onRefresh, modifier = Modifier.height(BoardStatusHeight), )- } else {- DepartureList(state.departures, now, onTrainTap)+ state.departures.isEmpty() -> {+ if (state.stale) StaleDeparturesBanner(state.fetchedAtMillis)+ EmptyState(+ title = stringResource(R.string.transit_departures_none),+ modifier = Modifier.height(BoardStatusHeight),+ )+ }+ else -> {+ if (state.stale) StaleDeparturesBanner(state.fetchedAtMillis)+ DepartureList(state.departures, now, onTrainTap)+ } } } }@@ -151,6 +165,21 @@ fun DeparturesSheet( } } +/** Stale indication above a last-good board (or a last-good empty board). */+@Composable+private fun StaleDeparturesBanner(fetchedAtMillis: Long?) {+ Text(+ if (fetchedAtMillis != null) {+ stringResource(R.string.transit_departures_stale_at, DepartureTime.clock(fetchedAtMillis))+ } else {+ stringResource(R.string.transit_departures_stale)+ },+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.error,+ modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),+ )+}+ /** * Every train through this stop, in the order they leave. *
maps/src/main/res/values/strings.xml
diff --git a/maps/src/main/res/values/strings.xml b/maps/src/main/res/values/strings.xmlindex 2cbaf68e7b..ceda40ab49 100644--- a/maps/src/main/res/values/strings.xml+++ b/maps/src/main/res/values/strings.xml@@ -295,6 +295,16 @@ <string name="transit_departures_loading">Loading departures\u2026</string> <!-- Departure board: shown when no upcoming departures were found. --> <string name="transit_departures_none">No upcoming departures</string>+ <!-- Departure board: live fetch failed and the board shown is the last-good one. -->+ <string name="transit_departures_stale">Live departures unavailable — showing the last board we fetched</string>+ <!-- Departure board: live fetch failed with the fetch time of the last-good board. %1$s = time, e.g. 5:04 PM -->+ <string name="transit_departures_stale_at">Live departures unavailable — last updated %1$s</string>+ <!-- Departure board: live fetch failed and no last-good board exists. -->+ <string name="transit_departures_unavailable_title">Departures unavailable</string>+ <!-- Departure board: explanation for the unavailable state. -->+ <string name="transit_departures_unavailable_message">Couldn\'t load live departures. Check your connection and try again.</string>+ <!-- Departure board: retry action for the unavailable state. -->+ <string name="transit_departures_retry">Retry</string> <!-- Departure board: platform/track label. %1$s = platform name e.g. "3" --> <string name="transit_platform">Platform %1$s</string> <!-- Departure board: a cancelled trip. -->
maps/src/test/java/com/vayunmathur/maps/data/transit/TransitousLastGoodTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/data/transit/TransitousLastGoodTest.kt b/maps/src/test/java/com/vayunmathur/maps/data/transit/TransitousLastGoodTest.ktnew file mode 100644index 0000000000..e7f451514a--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/data/transit/TransitousLastGoodTest.kt@@ -0,0 +1,76 @@+package com.vayunmathur.maps.data.transit++import kotlinx.coroutines.runBlocking+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Last-good serving in [TransitousDataSource]: failures must not blank a board that once loaded. */+class TransitousLastGoodTest {++ private val defaultFetch = TransitousDataSource.fetchStoptimes++ private fun dto() = MotisStoptimes(+ listOf(+ MotisStopTime(+ place = MotisPlace(+ name = "LastGood Station",+ scheduledDeparture = "2026-11-06T17:00:00+01:00",+ departure = "2026-11-06T17:00:00+01:00",+ ),+ routeShortName = "N",+ headsign = "Downtown",+ )+ )+ )++ private fun withFetch(fetch: suspend (String) -> MotisStoptimes?, block: suspend () -> Unit) = runBlocking {+ TransitousDataSource.fetchStoptimes = fetch+ try {+ block()+ } finally {+ TransitousDataSource.fetchStoptimes = defaultFetch+ }+ }++ @Test+ fun `a failure after a success serves last-good as stale`() {+ var fail = false+ withFetch({ if (fail) null else dto() }) {+ val stop = "lastgood-stale"+ val fresh = TransitousDataSource.departuresResult(stop)+ assertFalse(fresh.stale)+ assertEquals(1, fresh.departures.size)+ fail = true+ val stale = TransitousDataSource.departuresResult(stop, force = true)+ assertTrue(stale.stale)+ assertFalse(stale.unavailable)+ assertEquals(fresh.departures, stale.departures)+ assertEquals(fresh.fetchedAtMillis, stale.fetchedAtMillis)+ // The plain list API serves the same last-good board, not empty.+ assertEquals(1, TransitousDataSource.departures(stop, force = true).size)+ }+ }++ @Test+ fun `a failure with no last-good is unavailable not genuinely empty`() {+ withFetch({ null }) {+ val result = TransitousDataSource.departuresResult("lastgood-none", force = true)+ assertTrue(result.unavailable)+ assertFalse(result.stale)+ assertTrue(result.departures.isEmpty())+ assertEquals(result, TransitousDataSource.cachedResult("lastgood-none"))+ }+ }++ @Test+ fun `a genuinely empty success is neither stale nor unavailable`() {+ withFetch({ MotisStoptimes(emptyList()) }) {+ val result = TransitousDataSource.departuresResult("lastgood-empty", force = true)+ assertFalse(result.stale)+ assertFalse(result.unavailable)+ assertTrue(result.departures.isEmpty())+ }+ }+}