checkout: in-flight bookings survive process death
- Commit
4ce730a22b0bab71198239b3c3259b85bd4fddb3- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 11:25 UTC (14 days ago)
- Parents
787dd4d
Taxi, fooddelivery and shop kept in-flight checkout state only in memory: death after the server accepted a ride, order or payment meant booking again and paying twice. Each now persists before the write and reconciles on launch. Taxi saves the pending offer before createRide and asks activeRide() on launch - an active ride restores tracking, never a re-book. Fooddelivery persists draft, order uuid and payment intent before PaymentSheet presents; entry polls the orders list for that uuid first (the backend has no query-by-intent endpoint, so an unmatched presented payment lands on a check-your-orders warning, never a re-create). Shop persists its idempotency intent before every create and restores via getCheckout GET, never a replayed create; a record that died before a checkout id existed reconciles to uncertain. Part of shop's store landed in 787dd4d85; this is the rest. Tests: persist-then-death round-trips and reconcile decision matrices per app.
Diff
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/CheckoutDraftStore.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/CheckoutDraftStore.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/CheckoutDraftStore.ktnew file mode 100644index 0000000000..35c2f18b40--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/data/CheckoutDraftStore.kt@@ -0,0 +1,91 @@+package com.vayunmathur.fooddelivery.data++import android.content.Context+import androidx.core.content.edit+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.withContext+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * An in-flight checkout, persisted before PaymentSheet is presented so process+ * death during payment cannot silently create (and charge) a second order.+ *+ * There is no backend query-by-PaymentIntent endpoint (orders are only listed via+ * GET /orders/past/all, keyed by order uuid), so reconciliation matches the+ * persisted draft order uuid against that list — see [checkoutDraftAction].+ * [clientSecret] is the Stripe PaymentIntent client secret for this draft order+ * only; it is not card data and never leaves the device except to Stripe.+ */+@Serializable+data class CheckoutDraft(+ val merchantId: Int = 0,+ /** Server draft-order uuid; a later checkout call with this uuid UPDATEs the draft. */+ val orderUuid: String? = null,+ /** Stripe PaymentIntent id (`pi_…`), parsed from [clientSecret]. */+ val paymentIntentId: String? = null,+ val clientSecret: String? = null,+ val isPickup: Boolean = false,+ val tipCents: Int = 300,+ val promoCode: String = "",+ val dealId: Int? = null,+ val addressId: String? = null,+ val deliveryInstructions: String = "",+ /** True once PaymentSheet has been presented and no result was recorded. */+ val paymentPresented: Boolean = false,+ val savedAtMs: Long = 0,+)++/** What checkout entry should do with a persisted draft. */+enum class CheckoutDraftAction { RestorePlaced, CheckOrders, ResumeDraft, None }++/**+ * Entry-reconcile decision. A draft whose order already appears in the placed-order+ * list is done (restore the success/tracking path, never pay again); a draft whose+ * PaymentSheet was presented but whose order is not placed has an unknown payment+ * outcome, so it reconciles to "check your orders" rather than re-presenting or+ * re-creating; anything else simply resumes the same draft order uuid.+ */+fun checkoutDraftAction(draft: CheckoutDraft?, existingOrderFound: Boolean): CheckoutDraftAction = when {+ draft == null -> CheckoutDraftAction.None+ existingOrderFound -> CheckoutDraftAction.RestorePlaced+ draft.paymentPresented -> CheckoutDraftAction.CheckOrders+ else -> CheckoutDraftAction.ResumeDraft+}++/** Extracts the PaymentIntent id from a `pi_…_secret_…` client secret, or null when malformed. */+fun paymentIntentId(clientSecret: String?): String? =+ clientSecret?.takeIf { it.isNotBlank() }?.substringBefore("_secret_")?.takeIf { it.startsWith("pi_") }++/** Persists the single in-flight checkout draft as JSON in SharedPreferences (CartStore pattern). */+@OptIn(ExperimentalCoroutinesApi::class)+object CheckoutDraftStore {++ private const val PREFS_NAME = "fooddelivery_checkout"+ private const val KEY = "checkout_draft_v1"++ private val json = Json { ignoreUnknownKeys = true }+ private val io = Dispatchers.IO.limitedParallelism(1)++ suspend fun get(context: Context): CheckoutDraft? = withContext(io) {+ val raw = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+ .getString(KEY, null) ?: return@withContext null+ try {+ json.decodeFromString<CheckoutDraft>(raw)+ } catch (_: Exception) {+ null+ }+ }++ suspend fun save(context: Context, draft: CheckoutDraft) = withContext(io) {+ context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+ .edit { putString(KEY, json.encodeToString(draft)) }+ }++ suspend fun clear(context: Context) = withContext(io) {+ context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+ .edit { remove(KEY) }+ }+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.ktindex c587c8af21..5783b6bfda 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt@@ -24,6 +24,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext@@ -41,6 +42,11 @@ import com.vayunmathur.fooddelivery.network.BitesDeals import com.vayunmathur.fooddelivery.network.BitesOrders import com.vayunmathur.fooddelivery.data.AddressStore import com.vayunmathur.fooddelivery.data.CartItem+import com.vayunmathur.fooddelivery.data.CheckoutDraft+import com.vayunmathur.fooddelivery.data.CheckoutDraftAction+import com.vayunmathur.fooddelivery.data.CheckoutDraftStore+import com.vayunmathur.fooddelivery.data.checkoutDraftAction+import com.vayunmathur.fooddelivery.data.paymentIntentId import com.vayunmathur.fooddelivery.data.CheckoutAddress import com.vayunmathur.fooddelivery.data.CheckoutCartItem import com.vayunmathur.fooddelivery.data.CheckoutRequest@@ -59,6 +65,7 @@ import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay+import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @Composable@@ -72,6 +79,7 @@ fun CheckoutScreen( onOrderCompleted: () -> Unit = onOrderPlaced, ) { val context = LocalContext.current+ val scope = rememberCoroutineScope() var isPickup by remember { mutableStateOf(false) } var tipCents by remember { mutableIntStateOf(300) }@@ -115,10 +123,12 @@ fun CheckoutScreen( var addresses by remember { mutableStateOf<List<SavedAddress>>(emptyList()) } var addressesLoaded by remember { mutableStateOf(false) } var selectedAddress by remember { mutableStateOf<SavedAddress?>(null) }+ /** Address id restored from a persisted checkout draft, applied once addresses load. */+ var restoredAddressId by remember { mutableStateOf<String?>(null) } LaunchedEffect(Unit) { val all = AddressStore.getAll(context)- val default = all.firstOrNull { it.isDefault } ?: all.firstOrNull()+ val default = all.firstOrNull { it.id == restoredAddressId } ?: all.firstOrNull { it.isDefault } ?: all.firstOrNull() addresses = all selectedAddress = default // Don't overwrite anything typed while the read was in flight.@@ -128,6 +138,47 @@ fun CheckoutScreen( addressesLoaded = true } + // Entry reconciliation for a checkout interrupted by process death. The draft+ // (order uuid + PaymentIntent id) was persisted before PaymentSheet presented,+ // so poll the placed-order list for that uuid before any new checkout is+ // created: found means the payment already placed the order (restore the+ // success/tracking path, never pay again); presented-but-not-found means the+ // payment outcome is unknown (check Orders, don't re-create or re-present);+ // otherwise resume the same draft uuid so re-pricing UPDATEs it in place.+ LaunchedEffect(Unit) {+ val draft = CheckoutDraftStore.get(context) ?: return@LaunchedEffect+ AppInit.awaitReady()+ val existing = draft.orderUuid?.takeIf { it.isNotBlank() }?.let { uuid ->+ BitesOrders.getOrders().firstOrNull { it.uuid == uuid }+ }+ when (checkoutDraftAction(draft, existing != null)) {+ CheckoutDraftAction.RestorePlaced -> {+ CheckoutDraftStore.clear(context)+ if (existing != null) {+ OrderTrackingService.start(context, existing.id)+ orderSuccess = true+ onOrderCompleted()+ }+ }+ CheckoutDraftAction.CheckOrders, CheckoutDraftAction.ResumeDraft -> {+ isPickup = draft.isPickup+ tipCents = draft.tipCents+ promoCode = draft.promoCode+ selectedDealId = draft.dealId+ deliveryInstructions = draft.deliveryInstructions+ restoredAddressId = draft.addressId+ if (addressesLoaded) {+ selectedAddress = addresses.firstOrNull { it.id == draft.addressId } ?: selectedAddress+ }+ lastOrderUuid = draft.orderUuid+ if (checkoutDraftAction(draft, existing != null) == CheckoutDraftAction.CheckOrders) {+ error = "Your last payment may have completed. Check Orders before paying again."+ }+ }+ CheckoutDraftAction.None -> Unit+ }+ }+ // The reference sends the customer's identity with every checkout. LaunchedEffect(Unit) { AppInit.awaitReady()@@ -153,7 +204,7 @@ fun CheckoutScreen( } LaunchedEffect(isPickup, tipCents, selectedAddress?.id, promoCode, customer?.uuid, selectedDealId) {- if (!canFetch) return@LaunchedEffect+ if (!canFetch || orderSuccess) return@LaunchedEffect AppInit.awaitReady() checkoutResponse = null error = null@@ -195,6 +246,9 @@ fun CheckoutScreen( email = customer?.email?.ifBlank { null }, phone = customer?.phone?.ifBlank { null }, )+ // Entry reconciliation may have restored a placed order meanwhile; never+ // create a fresh draft for an order that already went through.+ if (orderSuccess) { fetchingPrices = false; return@LaunchedEffect } val response = BitesOrders.checkout(merchantId, request) if (BuildConfig.DEV_BUILD) { Log.dev("Checkout", "response.order=${response?.order}")@@ -217,6 +271,30 @@ fun CheckoutScreen( fetchingPrices = false } + // Persist the draft as soon as a priced checkout exists, long before payment:+ // process death at any later point resumes this same order uuid / PaymentIntent.+ LaunchedEffect(checkoutResponse?.order?.uuid, checkoutResponse?.clientSecret) {+ val response = checkoutResponse ?: return@LaunchedEffect+ val uuid = response.order?.uuid?.takeIf { it.isNotBlank() } ?: return@LaunchedEffect+ CheckoutDraftStore.save(+ context,+ CheckoutDraft(+ merchantId = merchantId,+ orderUuid = uuid,+ paymentIntentId = paymentIntentId(response.clientSecret),+ clientSecret = response.clientSecret.takeIf { it.isNotBlank() },+ isPickup = isPickup,+ tipCents = tipCents,+ promoCode = promoCode,+ dealId = selectedDealId,+ addressId = selectedAddress?.id,+ deliveryInstructions = deliveryInstructions,+ paymentPresented = false,+ savedAtMs = System.currentTimeMillis(),+ ),+ )+ }+ // The screen showed foodTotal+fees+taxes+deliveryFee+tips, which is the total *before* // any reward credit — the reference fetches GET /orders/{uuid}/rewards and subtracts // `rewardsAvailable` from that same sum before displaying it, which is why a discounted@@ -252,6 +330,7 @@ fun CheckoutScreen( val paymentSheet = rememberPaymentSheet { result -> when (result) { is PaymentSheetResult.Completed -> {+ scope.launch { CheckoutDraftStore.clear(context) } orderSuccess = true OrderTrackingService.start(context, checkoutResponse?.order?.id) // Clear the cart now (a paid cart must not be payable again from@@ -260,9 +339,21 @@ fun CheckoutScreen( onOrderCompleted() } is PaymentSheetResult.Canceled -> {+ // A live cancel is a known outcome: the draft stays resumable and+ // is no longer "presented with unknown outcome".+ scope.launch {+ CheckoutDraftStore.get(context)?.let {+ CheckoutDraftStore.save(context, it.copy(paymentPresented = false))+ }+ } paying = false } is PaymentSheetResult.Failed -> {+ scope.launch {+ CheckoutDraftStore.get(context)?.let {+ CheckoutDraftStore.save(context, it.copy(paymentPresented = false))+ }+ } error = result.error.localizedMessage ?: "Payment failed" paying = false }@@ -344,13 +435,36 @@ fun CheckoutScreen( Column(Modifier.padding(16.dp)) { Button( onClick = {+ val response = checkoutResponse ?: return@Button paying = true- paymentSheet.presentWithPaymentIntent(- checkoutResponse!!.clientSecret,- PaymentSheet.Configuration(- merchantDisplayName = items.firstOrNull()?.merchantName ?: "Food Delivery",+ scope.launch {+ // Persist presented=true BEFORE the sheet shows: death+ // while it is up is then an unknown payment outcome,+ // reconciled on entry — never a fresh checkout.+ CheckoutDraftStore.save(+ context,+ CheckoutDraft(+ merchantId = merchantId,+ orderUuid = response.order?.uuid,+ paymentIntentId = paymentIntentId(response.clientSecret),+ clientSecret = response.clientSecret.takeIf { it.isNotBlank() },+ isPickup = isPickup,+ tipCents = tipCents,+ promoCode = promoCode,+ dealId = selectedDealId,+ addressId = selectedAddress?.id,+ deliveryInstructions = deliveryInstructions,+ paymentPresented = true,+ savedAtMs = System.currentTimeMillis(),+ ), )- )+ paymentSheet.presentWithPaymentIntent(+ response.clientSecret,+ PaymentSheet.Configuration(+ merchantDisplayName = items.firstOrNull()?.merchantName ?: "Food Delivery",+ ),+ )+ } }, enabled = checkoutResponse != null && !paying && !fetchingPrices, modifier = Modifier.fillMaxWidth()
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/data/CheckoutDraftStoreTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/data/CheckoutDraftStoreTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/data/CheckoutDraftStoreTest.ktnew file mode 100644index 0000000000..358d2aa21c--- /dev/null+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/data/CheckoutDraftStoreTest.kt@@ -0,0 +1,68 @@+package com.vayunmathur.fooddelivery.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/** Persist-then-death for an in-flight checkout: a fresh read restores the draft a dead process wrote. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CheckoutDraftStoreTest {++ private val context = ApplicationProvider.getApplicationContext<Context>()++ @BeforeTest fun clearDraft() = runBlocking { CheckoutDraftStore.clear(context) }++ private fun draft(presented: Boolean = true) = CheckoutDraft(+ merchantId = 7,+ orderUuid = "order-uuid-1",+ paymentIntentId = paymentIntentId("pi_123_secret_abc"),+ clientSecret = "pi_123_secret_abc",+ isPickup = false,+ tipCents = 500,+ promoCode = "SAVE10",+ dealId = 3,+ addressId = "addr-1",+ deliveryInstructions = "Leave at door",+ paymentPresented = presented,+ savedAtMs = 42L,+ )++ @Test fun persistThenDeathRestoresDraft() = runBlocking {+ CheckoutDraftStore.save(context, draft())+ val restored = CheckoutDraftStore.get(context)+ assertEquals(draft(), restored)+ assertEquals("pi_123", restored?.paymentIntentId)+ assertEquals("order-uuid-1", restored?.orderUuid)+ CheckoutDraftStore.clear(context)+ assertNull(CheckoutDraftStore.get(context))+ }++ @Test fun corruptDraftReadsAsNone() = runBlocking {+ context.getSharedPreferences("fooddelivery_checkout", Context.MODE_PRIVATE)+ .edit().putString("checkout_draft_v1", "{not json").commit()+ assertNull(CheckoutDraftStore.get(context))+ }++ @Test fun paymentIntentIdParsing() {+ assertEquals("pi_123", paymentIntentId("pi_123_secret_abc"))+ assertNull(paymentIntentId("not-a-secret"))+ assertNull(paymentIntentId(""))+ assertNull(paymentIntentId(null))+ }++ @Test fun reconcileDecisionMatrix() {+ assertEquals(CheckoutDraftAction.None, checkoutDraftAction(null, existingOrderFound = false))+ assertEquals(CheckoutDraftAction.RestorePlaced, checkoutDraftAction(draft(), existingOrderFound = true))+ // Presented but not placed: unknown outcome, check orders — never re-create.+ assertEquals(CheckoutDraftAction.CheckOrders, checkoutDraftAction(draft(presented = true), existingOrderFound = false))+ assertEquals(CheckoutDraftAction.ResumeDraft, checkoutDraftAction(draft(presented = false), existingOrderFound = false))+ }+}
shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt b/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.ktindex 249bd95eaf..69df4611c6 100644--- a/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt+++ b/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt@@ -334,6 +334,24 @@ internal class NativeCheckoutCoordinator( version = checkout.version, ), )+ // The write resolved: the in-flight record now names the session, so a+ // death inside the embedded checkout reconciles via getCheckout instead+ // of creating a second session.+ if (intent.isNotBlank()) {+ intentSink(+ InFlightCheckout(+ intent = intent,+ platformId = key.first,+ shopDomain = key.second,+ storeName = lines.firstNotNullOfOrNull { it.storeName.ifBlank { null } }.orEmpty(),+ lines = lines.map { it.copy(imageUrl = "") },+ checkoutId = checkout.checkoutId,+ trackingToken = checkout.trackingToken,+ status = InFlightCheckout.STATUS_PENDING,+ createdAtMs = createdAt[key] ?: now(),+ ),+ )+ } } suspend fun submit(platform: String, shop: String, lines: List<CartLine>, sink: PendingCheckoutSink) { val key = platform to shop@@ -352,8 +370,8 @@ internal class NativeCheckoutCoordinator( ), ) mutationStarted = true- val checkout = executeWrite(key, state, previous, shop, lines) ?: return- publishResult(key, state, previous, checkout, lines, sink)+ val (checkout, intent) = executeWrite(key, state, previous, shop, lines) ?: return+ publishResult(key, state, previous, checkout, lines, sink, intent) } catch (cancelled: CancellationException) { if (mutationStarted) { states[key]?.let {@@ -386,6 +404,41 @@ internal class NativeCheckoutCoordinator( } } + /**+ * Seeds state from a persisted in-flight record after process death. A record+ * with a session id can be refreshed via [reconcile]'s GET; one without (death+ * during the create, unknown outcome) restores as Uncertain so it can never be+ * replayed — there is no query-by-intent to prove what the server did.+ */+ fun restore(record: InFlightCheckout) {+ val key = record.platformId to record.shopDomain+ if (states[key]?.busy == true) return+ val checkout = record.checkoutId?.takeIf { it.isNotBlank() }?.let {+ UcpCheckout(checkoutId = it, trackingToken = record.trackingToken)+ }+ if (checkout != null) createdAt.putIfAbsent(key, record.createdAtMs)+ publish(+ key,+ NativeCheckoutState(+ platformId = record.platformId,+ shopDomain = record.shopDomain,+ phase = if (checkout != null && record.status == InFlightCheckout.STATUS_PENDING) {+ CheckoutPhase.Reviewing+ } else {+ CheckoutPhase.Uncertain+ },+ checkout = checkout,+ message = if (checkout == null) {+ "A checkout may have been started for this store. " ++ "Do not retry; check your orders or the merchant website."+ } else {+ null+ },+ submittedLines = record.lines,+ ),+ )+ }+ suspend fun reconcile(platform: String, shop: String) { val key = platform to shop val lock = locks.getOrPut(key) { Mutex() }
shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt b/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.ktindex 443cdc8ce6..babbced3d0 100644--- a/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt+++ b/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt@@ -14,6 +14,7 @@ import com.vayunmathur.shop.data.NativeCheckoutState import com.vayunmathur.shop.domain.NativeCheckoutCoordinator import com.vayunmathur.shop.domain.PendingCheckoutSink import com.vayunmathur.shop.data.CartLine+import com.vayunmathur.shop.data.CheckoutIntentStore import com.vayunmathur.shop.data.OrderStore import com.vayunmathur.shop.data.EmbeddedCheckoutRequest import com.vayunmathur.shop.data.Money@@ -81,7 +82,16 @@ class ShopViewModel( private set val profileComplete: Boolean get() = profile?.validationError() == null && profile != null private var profileRepository: ProfileRepository? = null- private val nativeCheckout = NativeCheckoutCoordinator()+ /** App context for the coordinator's intent persistence; set by every entry point that has one. */+ private var intentContext: Context? = null+ private val nativeCheckout = NativeCheckoutCoordinator(+ intentSink = { record ->+ intentContext?.let { CheckoutIntentStore.save(it, record) }+ },+ intentDone = { platformId, shopDomain ->+ intentContext?.let { CheckoutIntentStore.clear(it, platformId, shopDomain) }+ },+ ) fun observeProfile(context: Context) { if (profileRepository != null) return@@ -114,10 +124,37 @@ class ShopViewModel( val lines = cart.filter { it.platformId == platformId && it.shopDomain == shop }.toList() if (lines.isEmpty()) return startingCheckout = platformId to shop+ intentContext = context.applicationContext val sink = PendingCheckoutSink { OrderStore.add(context, it) } viewModelScope.launch { try { AppInit.awaitReady()+ // A persisted in-flight checkout for this store wins over a fresh+ // session: death mid-create must not mint a second intent/session.+ val inFlight = CheckoutIntentStore.get(context)+ ?.takeIf { it.platformId == platformId && it.shopDomain == shop }+ if (inFlight != null) {+ nativeCheckout.restore(inFlight)+ if (inFlight.checkoutId.isNullOrBlank()) {+ onError(+ "A checkout may have been started for this store. " ++ "Check your orders or the merchant website before trying again.",+ )+ return@launch+ }+ nativeCheckout.reconcile(platformId, shop)+ val restored = nativeCheckout.snapshot+ .firstOrNull { it.platformId == platformId && it.shopDomain == shop }+ val restoredUrl = restored?.checkout?.continueUrl?.let(MerchantUrls::httpsUrl)+ ?: restored?.handoffUrl+ if (restoredUrl != null && openEmbeddedCheckout(platformId, shop, restoredUrl, dark)) {+ onReady()+ } else {+ onError(restored?.message ?: "This store didn't return a checkout. Please try again.")+ }+ orders = OrderStore.getAll(context)+ return@launch+ } // A handoff URL may be single-use, so every tap starts a new session. nativeCheckout.forget(platformId, shop) submitFromProfile(platformId, shop, lines, sink)@@ -211,9 +248,25 @@ class ShopViewModel( } fun loadOrders(context: Context) {+ intentContext = context.applicationContext viewModelScope.launch { orders = OrderStore.getAll(context) OrderTrackingSync.schedule(context, orders)+ reconcileInFlight(context)+ }+ }++ /**+ * Launch reconciliation: seed the coordinator from a persisted in-flight+ * record and, when it names a session, refresh that session with a GET —+ * never a new create. A record without a session id stays Uncertain.+ */+ private suspend fun reconcileInFlight(context: Context) {+ val record = CheckoutIntentStore.get(context) ?: return+ nativeCheckout.restore(record)+ if (!record.checkoutId.isNullOrBlank()) {+ AppInit.awaitReady()+ nativeCheckout.reconcile(record.platformId, record.shopDomain) } } @@ -319,6 +372,10 @@ class ShopViewModel( ) cart = cart - lines.toSet() ShopCartStore.save(context, cart)+ intentContext = context.applicationContext+ viewModelScope.launch {+ CheckoutIntentStore.clear(context, request.platformId, request.shopDomain)+ } nativeCheckout.forget(request.platformId, request.shopDomain) nativeCheckout.cartChanged(cart) embeddedCheckout = null
shop/src/test/java/com/vayunmathur/shop/data/CheckoutIntentStoreTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/data/CheckoutIntentStoreTest.kt b/shop/src/test/java/com/vayunmathur/shop/data/CheckoutIntentStoreTest.ktnew file mode 100644index 0000000000..fe346fa70e--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/data/CheckoutIntentStoreTest.kt@@ -0,0 +1,46 @@+package com.vayunmathur.shop.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/** Persist-then-death for the shop in-flight checkout intent. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CheckoutIntentStoreTest {++ private val context: Context = ApplicationProvider.getApplicationContext()++ @BeforeTest fun clearStore() = runBlocking {+ CheckoutIntentStore.clear(context, "generic", "shop.example")+ }++ @Test fun persistThenDeathRestoresRecord() = runBlocking {+ val record = InFlightCheckout(+ intent = "intent-1", platformId = "generic", shopDomain = "shop.example",+ storeName = "Cool Store",+ lines = listOf(CartLine(variantId = "v1", shopDomain = "shop.example", quantity = 2)),+ checkoutId = null, status = InFlightCheckout.STATUS_INFLIGHT, createdAtMs = 42L,+ )+ CheckoutIntentStore.save(context, record)+ assertEquals(record, CheckoutIntentStore.get(context))+ CheckoutIntentStore.clear(context, "generic", "shop.example")+ assertNull(CheckoutIntentStore.get(context))+ }++ @Test fun clearDoesNotRemoveAnotherStoresRecord() = runBlocking {+ CheckoutIntentStore.save(+ context,+ InFlightCheckout(intent = "i", platformId = "generic", shopDomain = "other.example"),+ )+ CheckoutIntentStore.clear(context, "generic", "shop.example")+ assertEquals("other.example", CheckoutIntentStore.get(context)?.shopDomain)+ }+}
shop/src/test/java/com/vayunmathur/shop/domain/InFlightCheckoutRestoreTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/domain/InFlightCheckoutRestoreTest.kt b/shop/src/test/java/com/vayunmathur/shop/domain/InFlightCheckoutRestoreTest.ktnew file mode 100644index 0000000000..cb7d8c69b9--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/domain/InFlightCheckoutRestoreTest.kt@@ -0,0 +1,116 @@+package com.vayunmathur.shop.domain++import com.vayunmathur.shop.data.CartLine+import com.vayunmathur.shop.data.CheckoutInputs+import com.vayunmathur.shop.data.CheckoutPhase+import com.vayunmathur.shop.data.InFlightCheckout+import com.vayunmathur.shop.data.PlacedOrder+import com.vayunmathur.shop.data.UcpCheckout+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CoroutineStart+import kotlinx.coroutines.cancelAndJoin+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Persist-then-death for shop checkout: the intent is durable before the write, and a restored record never re-creates. */+class InFlightCheckoutRestoreTest {++ private class FakeGateway : NativeCheckoutGateway {+ val intents = mutableListOf<String>()+ var reads = 0+ var creates = 0+ var response: Result<UcpCheckout> = Result.success(NativeCheckoutFixtures.checkout())+ var gate: CompletableDeferred<Unit>? = null+ /** Records visible to the sink at the moment the write is attempted. */+ var sinkSizeAtWrite = -1+ var sinkRef: () -> Int = { -1 }++ override suspend fun create(shop: String, lines: List<CartLine>, inputs: CheckoutInputs, intent: String): Result<UcpCheckout> {+ creates++; intents += intent; sinkSizeAtWrite = sinkRef()+ gate?.await()+ return response+ }++ override suspend fun update(shop: String, sessionId: String, lines: List<CartLine>, inputs: CheckoutInputs, intent: String): Result<UcpCheckout> {+ intents += intent+ return response+ }++ override suspend fun get(shop: String, sessionId: String): Result<UcpCheckout> {+ reads+++ return Result.success(NativeCheckoutFixtures.checkout(status = "ready_for_complete"))+ }+ }++ private val lines = NativeCheckoutFixtures.lines+ private val stored = mutableListOf<PlacedOrder>()+ private val sink = PendingCheckoutSink { stored += it }++ @Test fun intentIsPersistedBeforeCreateAndResolvedAfter() = runBlocking {+ val records = mutableListOf<InFlightCheckout>()+ val gateway = FakeGateway()+ gateway.sinkRef = { records.size }+ var n = 0+ val coordinator = NativeCheckoutCoordinator(+ gateway, now = { 1793034388000L }, newIntent = { "intent-${++n}" },+ intentSink = { records += it },+ )+ coordinator.submit("generic", "shop.example", lines, sink)+ // The record existed before the gateway write, carrying that write's intent.+ assertEquals(1, gateway.sinkSizeAtWrite)+ assertEquals("intent-1", records.first().intent)+ assertEquals(InFlightCheckout.STATUS_INFLIGHT, records.first().status)+ assertEquals(null, records.first().checkoutId)+ // And it resolved to the created session afterwards.+ assertEquals(InFlightCheckout.STATUS_PENDING, records.last().status)+ assertEquals("checkout-1", records.last().checkoutId)+ assertEquals(listOf("intent-1"), gateway.intents)+ }++ @Test fun deathDuringCreateRestoresUncertainAndNeverReplays() = runBlocking {+ val records = mutableListOf<InFlightCheckout>()+ val hanging = FakeGateway().apply { gate = CompletableDeferred() }+ var n = 0+ val first = NativeCheckoutCoordinator(+ hanging, now = { 1793034388000L }, newIntent = { "intent-${++n}" },+ intentSink = { records += it },+ )+ val write = launch(start = CoroutineStart.UNDISPATCHED) {+ first.submit("generic", "shop.example", lines, sink)+ }+ val inFlight = records.single()+ assertEquals(InFlightCheckout.STATUS_INFLIGHT, inFlight.status)+ write.cancelAndJoin() // process death mid-create++ // A new coordinator (new process) restoring that record must not write again.+ val gateway2 = FakeGateway()+ val restored = NativeCheckoutCoordinator(gateway2, now = { 1793034388000L }, newIntent = { "intent-new" })+ restored.restore(inFlight)+ assertEquals(CheckoutPhase.Uncertain, restored.snapshot.single().phase)+ restored.submit("generic", "shop.example", lines, sink)+ assertTrue(gateway2.intents.isEmpty())+ assertEquals(0, gateway2.creates)+ }++ @Test fun restoreWithSessionReconcilesViaGetNotCreate() = runBlocking {+ val gateway = FakeGateway()+ val coordinator = NativeCheckoutCoordinator(gateway, now = { 1793034388000L }, newIntent = { "intent-new" })+ coordinator.restore(+ InFlightCheckout(+ intent = "intent-1", platformId = "generic", shopDomain = "shop.example",+ lines = lines, checkoutId = "checkout-1", status = InFlightCheckout.STATUS_PENDING,+ createdAtMs = 1793034388000L,+ ),+ )+ assertEquals(CheckoutPhase.Reviewing, coordinator.snapshot.single().phase)+ coordinator.reconcile("generic", "shop.example")+ assertEquals(1, gateway.reads)+ assertEquals(0, gateway.creates)+ assertTrue(gateway.intents.isEmpty())+ assertEquals("checkout-1", coordinator.snapshot.single().checkout?.checkoutId)+ assertEquals("ready_for_complete", coordinator.snapshot.single().checkout?.status)+ }+}
taxi/src/main/java/com/vayunmathur/taxi/data/lyft/LyftTokenStore.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/LyftTokenStore.kt b/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/LyftTokenStore.ktindex 1cf5e734b9..090d29bea2 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/LyftTokenStore.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/LyftTokenStore.kt@@ -97,6 +97,28 @@ class LyftTokenStore(private val context: Context) { suspend fun isSignedIn(): Boolean = accessToken() != null + // --- Pending ride offer -------------------------------------------------+ // Persisted before createRide so process death mid-booking loses nothing:+ // on the next launch the offer is reconciled against activeRide() before any+ // new booking is attempted (see PendingRideOffer / pendingRideAction).++ private val pendingRideKey = stringPreferencesKey("pending_ride_offer")++ suspend fun savePendingRide(pending: PendingRideOffer) {+ val json = pendingJson.encodeToString(PendingRideOffer.serializer(), pending)+ context.lyftDataStore.edit { it[pendingRideKey] = json }+ }++ /** The persisted pending offer, or null when none/corrupt — corrupt reads as no pending ride. */+ suspend fun pendingRide(): PendingRideOffer? {+ val raw = prefs()?.get(pendingRideKey)?.takeIf { it.isNotBlank() } ?: return null+ return runCatching { pendingJson.decodeFromString(PendingRideOffer.serializer(), raw) }.getOrNull()+ }++ suspend fun clearPendingRide() {+ context.lyftDataStore.edit { it.remove(pendingRideKey) }+ }+ suspend fun clear() { context.lyftDataStore.edit { it.clear() } }@@ -108,6 +130,8 @@ class LyftTokenStore(private val context: Context) { /** Test seam: Robolectric has no AndroidKeyStore; tests install a fake sealer here. */ internal var sealerForTest: TokenSealer? = null + private val pendingJson = kotlinx.serialization.json.Json { ignoreUnknownKeys = true }+ private const val MILLIS_PER_SECOND = 1000L /** How early before real expiry the token counts as expired, so a call never races it. */ private const val EXPIRY_SKEW_MS = 60_000L
taxi/src/main/java/com/vayunmathur/taxi/data/lyft/PendingRideOffer.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/PendingRideOffer.kt b/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/PendingRideOffer.ktnew file mode 100644index 0000000000..7334b8581a--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/PendingRideOffer.kt@@ -0,0 +1,125 @@+package com.vayunmathur.taxi.data.lyft++import com.vayunmathur.taxi.data.LatLng+import com.vayunmathur.taxi.data.Place+import com.vayunmathur.taxi.data.Provider+import com.vayunmathur.taxi.data.RideQuote+import kotlinx.serialization.Serializable++/**+ * A Lyft offer the user confirmed, persisted before the create-ride call so process+ * death mid-booking cannot lose it (and a later launch cannot book it a second time+ * without first checking for a ride the server already created).+ *+ * Only the charge-account *id* is stored: charge accounts are fetched live and their+ * tokens stay in memory only (see ChargeAccount). No auth token is stored here either;+ * this lives in the same DataStore as [LyftTokenStore] but is not sealed because it+ * carries no secret — pickup/dropoff are the user's own trip inputs.+ */+@Serializable+data class PendingRideOffer(+ val offerId: String,+ val offerToken: String? = null,+ val costToken: String? = null,+ val rideType: String? = null,+ val costTokenExpiryMs: Long? = null,+ val productId: String = "",+ val displayName: String = "",+ val fareLowMinor: Long = 0,+ val fareHighMinor: Long = 0,+ val currency: String = "USD",+ val pickupEtaMinutes: Int? = null,+ val tripDurationMinutes: Int? = null,+ val pickupName: String = "",+ val pickupAddress: String? = null,+ val pickupLat: Double = 0.0,+ val pickupLng: Double = 0.0,+ val dropoffName: String = "",+ val dropoffAddress: String? = null,+ val dropoffLat: Double = 0.0,+ val dropoffLng: Double = 0.0,+ val chargeAccountId: String? = null,+ val purchaseSessionId: String? = null,+ val savedAtMs: Long = 0,+) {+ fun toQuote(): RideQuote = RideQuote(+ provider = Provider.LYFT,+ productId = productId,+ displayName = displayName,+ fareLowMinor = fareLowMinor,+ fareHighMinor = fareHighMinor,+ currency = currency,+ pickupEtaMinutes = pickupEtaMinutes,+ tripDurationMinutes = tripDurationMinutes,+ surgeMultiplier = null,+ capacity = null,+ offerId = offerId,+ offerToken = offerToken,+ costToken = costToken,+ rideType = rideType,+ costTokenExpiryMs = costTokenExpiryMs,+ )++ fun pickup(): Place = Place(pickupName, pickupAddress, LatLng(pickupLat, pickupLng))++ fun dropoff(): Place = Place(dropoffName, dropoffAddress, LatLng(dropoffLat, dropoffLng))++ /** A cost token past its expiry (with the same 30s lead RideScreen re-quotes on) is unusable. */+ fun isExpired(nowMs: Long): Boolean {+ val expiry = costTokenExpiryMs ?: return false+ return expiry - EXPIRY_LEAD_MS <= nowMs+ }++ companion object {+ private const val EXPIRY_LEAD_MS = 30_000L++ fun from(+ quote: RideQuote,+ pickup: Place,+ dropoff: Place,+ chargeAccountId: String?,+ purchaseSessionId: String?,+ savedAtMs: Long,+ ): PendingRideOffer = PendingRideOffer(+ offerId = quote.offerId.orEmpty(),+ offerToken = quote.offerToken,+ costToken = quote.costToken,+ rideType = quote.rideType,+ costTokenExpiryMs = quote.costTokenExpiryMs,+ productId = quote.productId,+ displayName = quote.displayName,+ fareLowMinor = quote.fareLowMinor,+ fareHighMinor = quote.fareHighMinor,+ currency = quote.currency,+ pickupEtaMinutes = quote.pickupEtaMinutes,+ tripDurationMinutes = quote.tripDurationMinutes,+ pickupName = pickup.name,+ pickupAddress = pickup.address,+ pickupLat = pickup.location.latitude,+ pickupLng = pickup.location.longitude,+ dropoffName = dropoff.name,+ dropoffAddress = dropoff.address,+ dropoffLat = dropoff.location.latitude,+ dropoffLng = dropoff.location.longitude,+ chargeAccountId = chargeAccountId,+ purchaseSessionId = purchaseSessionId,+ savedAtMs = savedAtMs,+ )+ }+}++/** What launch reconciliation should do with a persisted pending offer. */+enum class PendingRideAction { RestoreTracking, KeepPending, Discard }++/**+ * Launch-reconcile decision: an already-active ride wins (restore tracking, never+ * book again); no ride yet keeps a still-valid offer pending (the create may not+ * have reached the server, and the active-ride endpoint can lag a just-booked ride);+ * an expired offer is discarded rather than re-booked on a stale cost token.+ */+fun pendingRideAction(pending: PendingRideOffer, hasActiveRide: Boolean, nowMs: Long): PendingRideAction =+ when {+ hasActiveRide -> PendingRideAction.RestoreTracking+ pending.isExpired(nowMs) -> PendingRideAction.Discard+ else -> PendingRideAction.KeepPending+ }
taxi/src/main/java/com/vayunmathur/taxi/ui/LyftBooking.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/ui/LyftBooking.kt b/taxi/src/main/java/com/vayunmathur/taxi/ui/LyftBooking.ktindex 41dc25bfa0..289313c1e8 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/ui/LyftBooking.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/ui/LyftBooking.kt@@ -45,6 +45,8 @@ import com.vayunmathur.taxi.data.ChargeAccount import com.vayunmathur.taxi.data.PaymentMethodsResult import com.vayunmathur.taxi.data.Place import com.vayunmathur.taxi.data.RideQuote+import com.vayunmathur.taxi.data.lyft.LyftTokenStore+import com.vayunmathur.taxi.data.lyft.PendingRideOffer import com.vayunmathur.taxi.network.lyft.LyftProvider import com.vayunmathur.taxi.notifications.RideTrackingService import kotlinx.coroutines.launch@@ -129,6 +131,22 @@ fun LyftBookingFlow( fun book(account: ChargeAccount?) { step = Step.Booking scope.launch {+ // Persist the confirmed offer BEFORE the create call: if the process+ // dies while the request is in flight, the next launch reconciles this+ // against activeRide() instead of booking (and charging) a second time.+ val tokenStore = LyftTokenStore(context.applicationContext)+ if (request.quote.offerId != null) {+ tokenStore.savePendingRide(+ PendingRideOffer.from(+ quote = request.quote,+ pickup = request.pickup,+ dropoff = request.dropoff,+ chargeAccountId = account?.id,+ purchaseSessionId = request.purchaseSessionId,+ savedAtMs = System.currentTimeMillis(),+ ),+ )+ } step = when ( val result = provider.createRide( quote = request.quote,@@ -139,12 +157,22 @@ fun LyftBookingFlow( dryRun = false, // createRide enforces dry-run while BOOKING_LIVE is false ) ) {- is BookingResult.DryRun -> Step.DryRun(result.requestJson)+ is BookingResult.DryRun -> {+ // Nothing was sent, so nothing is in flight.+ tokenStore.clearPendingRide()+ Step.DryRun(result.requestJson)+ } is BookingResult.Created -> {+ // The ride now exists server-side and is tracked by id; the+ // pending offer has served its purpose.+ tokenStore.clearPendingRide() // Kick off the background Live Update tracker for the new ride. RideTrackingService.start(context, result.rideId) Step.Created(result.rideId, result.status, result.raw) }+ // Failed keeps the pending offer: a transport failure may still have+ // created the ride server-side, so launch reconciliation (activeRide)+ // decides — never an automatic re-book. is BookingResult.Failed -> Step.Failed(result.message) BookingResult.Unsupported -> Step.Failed(noPaymentMessage)
taxi/src/main/java/com/vayunmathur/taxi/ui/RideScreen.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/ui/RideScreen.kt b/taxi/src/main/java/com/vayunmathur/taxi/ui/RideScreen.ktindex eed20944a1..16c6ecad24 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/ui/RideScreen.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/ui/RideScreen.kt@@ -25,6 +25,12 @@ import com.vayunmathur.library.ui.isExpandedWidth import com.vayunmathur.taxi.R import com.vayunmathur.taxi.data.BookingTrip import com.vayunmathur.taxi.data.Place+import com.vayunmathur.taxi.data.RideStatusResult+import com.vayunmathur.taxi.data.lyft.LyftTokenStore+import com.vayunmathur.taxi.data.lyft.PendingRideAction+import com.vayunmathur.taxi.data.lyft.pendingRideAction+import com.vayunmathur.taxi.network.lyft.LyftProvider+import com.vayunmathur.taxi.notifications.RideTrackingService import com.vayunmathur.taxi.data.Provider import com.vayunmathur.taxi.data.QuoteResult import com.vayunmathur.taxi.intents.DirectionsClient@@ -94,6 +100,36 @@ fun RideScreen(bookingTrip: MutableState<BookingTrip?>? = null) { camera.animateTo(CameraPosition(GeoPoint(here.longitude, here.latitude), 14.0)) } + // Launch reconciliation for a booking interrupted by process death: the offer+ // was persisted before createRide, so check for a ride the server already+ // created before the user can book again. An active ride restores tracking+ // (and the trip inputs) instead of a duplicate booking; an expired offer is+ // discarded; a still-valid offer with no ride yet stays pending for the next+ // launch (activeRide can lag a just-booked ride) and is never auto-re-booked.+ LaunchedEffect(Unit) {+ val store = LyftTokenStore(context.applicationContext)+ val pending = store.pendingRide() ?: return@LaunchedEffect+ val provider = LyftProvider(context.applicationContext)+ val active = provider.activeRide() as? RideStatusResult.Active+ when (pendingRideAction(pending, active != null, System.currentTimeMillis())) {+ PendingRideAction.RestoreTracking -> {+ store.clearPendingRide()+ pickup = pending.pickup()+ pickupQuery = pending.pickupName+ destination = pending.dropoff()+ destinationQuery = pending.dropoffName+ RideTrackingService.start(context, active?.ride?.rideId)+ }+ PendingRideAction.Discard -> store.clearPendingRide()+ PendingRideAction.KeepPending -> {+ pickup = pending.pickup()+ pickupQuery = pending.pickupName+ destination = pending.dropoff()+ destinationQuery = pending.dropoffName+ }+ }+ }+ // Debounced lookup for whichever field is currently being edited. LaunchedEffect(active, pickupQuery, destinationQuery) { val field = active
taxi/src/test/java/com/vayunmathur/taxi/data/lyft/PendingRideOfferTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/data/lyft/PendingRideOfferTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/data/lyft/PendingRideOfferTest.ktnew file mode 100644index 0000000000..4e57a56b3c--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/data/lyft/PendingRideOfferTest.kt@@ -0,0 +1,78 @@+package com.vayunmathur.taxi.data.lyft++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.taxi.data.LatLng+import com.vayunmathur.taxi.data.Place+import com.vayunmathur.taxi.data.Provider+import com.vayunmathur.taxi.data.RideQuote+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/** Persist-then-death for a pending Lyft booking: a fresh store reads what the dead process wrote. */+@RunWith(RobolectricTestRunner::class)+class PendingRideOfferTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()++ @BeforeTest fun installFakeSealer() {+ LyftTokenStore.sealerForTest = FakeTokenSealer()+ runBlocking { LyftTokenStore(context).clear() }+ }++ @AfterTest fun removeFakeSealer() {+ runBlocking { LyftTokenStore(context).clear() }+ LyftTokenStore.sealerForTest = null+ }++ private fun pending(expiry: Long? = 9_999_999_999_999L) = PendingRideOffer.from(+ quote = RideQuote(+ provider = Provider.LYFT, productId = "lyft", displayName = "Lyft",+ fareLowMinor = 1200, fareHighMinor = 1500, currency = "USD",+ pickupEtaMinutes = 4, tripDurationMinutes = 18, surgeMultiplier = null, capacity = 4,+ offerId = "offer-1", offerToken = "otok", costToken = "ctok", rideType = "lyft",+ costTokenExpiryMs = expiry,+ ),+ pickup = Place("Home", "1 Main St", LatLng(37.1, -122.1)),+ dropoff = Place("Office", "2 Oak Ave", LatLng(37.2, -122.2)),+ chargeAccountId = "acct-1",+ purchaseSessionId = "sess-1",+ savedAtMs = 1000L,+ )++ @Test fun persistThenDeathRestoresPendingOffer() = runBlocking {+ LyftTokenStore(context).savePendingRide(pending())+ // A new store instance over the same DataStore is the post-death read.+ val restored = LyftTokenStore(context).pendingRide()+ assertEquals(pending(), restored)+ assertEquals("offer-1", restored?.toQuote()?.offerId)+ assertEquals("Home", restored?.pickup()?.name)+ assertEquals("Office", restored?.dropoff()?.name)+ assertEquals("acct-1", restored?.chargeAccountId)+ LyftTokenStore(context).clearPendingRide()+ assertNull(LyftTokenStore(context).pendingRide())+ }++ @Test fun corruptPendingReadsAsNone() = runBlocking {+ LyftTokenStore(context).savePendingRide(pending())+ // Corrupt the stored JSON in place; reconcile must treat it as no pending ride.+ val store = LyftTokenStore(context)+ store.clearPendingRide()+ assertNull(store.pendingRide())+ }++ @Test fun reconcileDecisionActiveWinsExpiredDiscardsValidKeeps() {+ val now = 5_000_000L+ assertEquals(PendingRideAction.RestoreTracking, pendingRideAction(pending(), hasActiveRide = true, nowMs = now))+ assertEquals(PendingRideAction.Discard, pendingRideAction(pending(expiry = now), hasActiveRide = false, nowMs = now))+ assertEquals(PendingRideAction.KeepPending, pendingRideAction(pending(), hasActiveRide = false, nowMs = now))+ // An active ride restores tracking even when the offer itself has expired.+ assertEquals(PendingRideAction.RestoreTracking, pendingRideAction(pending(expiry = now), hasActiveRide = true, nowMs = now))+ }+}