Modern Apps git

← Modern-Apps.git

taxi: one transient server error no longer kills background ride tracking forever

Commit
ec12b4f72c8c0713ddfd00a798c9d13deb4b7fbe
Author
Vayun Mathur <[email protected]>
When
2026-12-01 03:56 UTC (5 days ago)
Parents
91012fe
The tracked-ride fallback collapsed every non-Active result
into 'gone' via an as? Active cast: when activeride 404'd and
the by-id poll returned HTTP 500, the result cast to null,
ended=true, finish() cancelled the notification, removed the
foreground service and stopSelf() โ€” so the next (successful)
poll never happened. That is the background case, the
service's whole purpose. The same file already treated a
primary Failed as transient, and the tracking screen's
identical fallback had been fixed; the service was missed.

byIdFallback now maps Failed -> keep polling with the last
notification, None/Unsupported -> end; terminal rides still
stop via the existing isTerminal + linger path. Three
decision tests plus a service test (404 -> by-id 500 then 200
'approaching'; asserts the second by-id call happens, which
failed pre-fix). Fares, ETAs, cost tokens, payment and
location paths were audited and cleared. Verified:
:taxi:testDevUnitTest 264 tests pass; lint errors are
pre-existing on untouched files.

Diff

taxi/src/main/java/com/vayunmathur/taxi/notifications/RideTrackingService.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/notifications/RideTrackingService.kt b/taxi/src/main/java/com/vayunmathur/taxi/notifications/RideTrackingService.ktindex 49cb343563..0284fd5ea0 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/notifications/RideTrackingService.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/notifications/RideTrackingService.kt@@ -77,10 +77,16 @@ class RideTrackingService : Service() {                 is RideStatusResult.Active -> result.ride                 RideStatusResult.None -> {                     // The active-ride endpoint may not surface a just-booked ride; read it-                    // directly by id before giving up.-                    val byId = provider.rideById(rideId) as? RideStatusResult.Active-                    if (byId == null) ended = true-                    byId?.ride+                    // directly by id before giving up. A transient by-id failure must not+                    // end background tracking (mirroring the active-ride Failed branch+                    // above and RideTrackingScreen's fallback): only a ride that is+                    // genuinely gone (None) or Unsupported ends the loop.+                    val fallback = byIdFallback(provider.rideById(rideId))+                    if (fallback.ended) ended = true+                    if (fallback.failureMessage != null) {+                        Log.status(TAG, "rideById failed: ${fallback.failureMessage}")+                    }+                    fallback.ride                 }                 is RideStatusResult.Failed -> {                     Log.status(TAG, "activeRide failed: ${result.message}")@@ -185,3 +191,24 @@ class RideTrackingService : Service() {         }     } }++/** Outcome of the by-id fallback after the active-ride endpoint reports no ride. */+internal data class ByIdFallback(+    val ride: ActiveRide?,+    val ended: Boolean,+    val failureMessage: String? = null,+)++/**+ * Maps a by-id read onto the service's stop/continue decision. [RideStatusResult.Failed]+ * is transient (rate limit, 5xx, transport blip โ€” the ride may still be live), so it+ * keeps polling with the last notification in place; only+ * [RideStatusResult.None] (ride genuinely gone) and [RideStatusResult.Unsupported]+ * end tracking.+ */+internal fun byIdFallback(result: RideStatusResult): ByIdFallback = when (result) {+    is RideStatusResult.Active -> ByIdFallback(ride = result.ride, ended = false)+    is RideStatusResult.Failed -> ByIdFallback(ride = null, ended = false, failureMessage = result.message)+    RideStatusResult.None -> ByIdFallback(ride = null, ended = true)+    RideStatusResult.Unsupported -> ByIdFallback(ride = null, ended = true)+}
taxi/src/test/java/com/vayunmathur/taxi/notifications/RideTrackingServiceFallbackTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/notifications/RideTrackingServiceFallbackTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/notifications/RideTrackingServiceFallbackTest.ktnew file mode 100644index 0000000000..8c37a32b9b--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/notifications/RideTrackingServiceFallbackTest.kt@@ -0,0 +1,141 @@+package com.vayunmathur.taxi.notifications++import android.content.Context+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.taxi.data.ActiveRide+import com.vayunmathur.taxi.data.RideStatus+import com.vayunmathur.taxi.data.RideStatusResult+import com.vayunmathur.taxi.data.lyft.FakeTokenSealer+import com.vayunmathur.taxi.data.lyft.LyftTokenStore+import com.vayunmathur.taxi.network.TaxiPass3FakeHttp+import com.vayunmathur.taxi.network.lyft.LyftToken+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.util.concurrent.atomic.AtomicInteger+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertSame+import kotlin.test.assertTrue++/**+ * Regression: the foreground tracking service fell back to a by-id read when the+ * active-ride endpoint reported no ride, and ended itself on *any* non-Active+ * by-id result โ€” including a transient [RideStatusResult.Failed] (HTTP 500).+ * The tracking screen's identical fallback was fixed to keep polling on Failed;+ * the service, which is the only tracker once the app is backgrounded, was not.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class RideTrackingServiceFallbackTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private val http = TaxiPass3FakeHttp()++    private fun ride(status: RideStatus = RideStatus.APPROACHING) = ActiveRide(+        rideId = "r1",+        status = status,+        statusRaw = status.wire,+        driver = null,+        vehicle = null,+        driverLocation = null,+        stops = emptyList(),+        raw = "",+    )++    @Test+    fun byIdFallbackFailedKeepsTracking() {+        val fallback = byIdFallback(RideStatusResult.Failed("Lyft returned HTTP 500: kaput"))+        assertFalse(fallback.ended)+        assertNull(fallback.ride)+        assertEquals("Lyft returned HTTP 500: kaput", fallback.failureMessage)+    }++    @Test+    fun byIdFallbackNoneAndUnsupportedEndTracking() {+        assertTrue(byIdFallback(RideStatusResult.None).ended)+        assertNull(byIdFallback(RideStatusResult.None).ride)+        assertTrue(byIdFallback(RideStatusResult.Unsupported).ended)+        assertNull(byIdFallback(RideStatusResult.Unsupported).ride)+    }++    @Test+    fun byIdFallbackActiveReturnsRideWithoutEnding() {+        val active = ride()+        val fallback = byIdFallback(RideStatusResult.Active(active))+        assertFalse(fallback.ended)+        assertSame(active, fallback.ride)+        assertNull(fallback.failureMessage)+        // A terminal ride is returned the same way: the poll loop's own+        // isTerminal check (with its linger) owns stopping for it.+        val terminal = ride(RideStatus.COMPLETED)+        assertSame(terminal, byIdFallback(RideStatusResult.Active(terminal)).ride)+    }++    @BeforeTest+    fun setUp() {+        LyftTokenStore.sealerForTest = FakeTokenSealer()+        http.install()+        runBlocking {+            LyftTokenStore(context).save(+                LyftToken(accessToken = "access-tok", refreshToken = "rt", expiresIn = 3600),+            )+        }+    }++    @AfterTest+    fun tearDown() {+        http.uninstall()+        runBlocking { LyftTokenStore(context).clear() }+        LyftTokenStore.sealerForTest = null+    }++    private fun rideJson(status: String): String =+        """{"ride":{"ride_id":"r1","status":"$status",+          "driver":{"first_name":"Jo","last_name":"Smith"},+          "location":{"lat":37.7,"lng":-122.4}}}"""++    @Test+    fun serviceRecoversAfterTransientByIdFailure() {+        // Exact failing state: active-ride 404s (ride not surfaced yet), the+        // first by-id read 500s transiently, the next succeeds. Before the+        // fix the service finished on the 500 and never made the second call.+        http.on("/v1/activeride") { http.raw(404, "none", "text/plain", it.url) }+        val attempts = AtomicInteger()+        http.on("/v1/rides/") {+            if (attempts.incrementAndGet() <= 1) {+                http.raw(500, "kaput", "text/plain", it.url)+            } else {+                http.raw(200, rideJson("approaching"), url = it.url)+            }+        }+        val controller = Robolectric.buildService(RideTrackingService::class.java)+        try {+            val service = controller.create().get()+            service.onStartCommand(+                Intent(context, RideTrackingService::class.java).putExtra("ride_id", "r1"),+                0,+                1,+            )+            // Deadline-polling for the service's real 5s poll cadence.+            val deadline = System.currentTimeMillis() + 15_000+            while (http.callsTo("/v1/rides/").size < 2 && System.currentTimeMillis() < deadline) {+                Thread.sleep(50)+            }+            assertTrue(+                http.callsTo("/v1/rides/").size >= 2,+                "transient by-id 500 ended background tracking after " ++                    "${http.callsTo("/v1/rides/").size} by-id call(s)",+            )+        } finally {+            controller.destroy()+        }+    }+}