Modern Apps git

← Modern-Apps.git

appstore: pace Play requests and wait out 429s (#596)

Commit
43342e27be2ba8b0f36b409db6db2faef99c7aff
Author
vayun-mathur <[email protected]>
When
2026-09-07 04:01 UTC (3 months ago)
Parents
e4e01b5

Diff

appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayHttpClient.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayHttpClient.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayHttpClient.ktindex a2196859e3..bdc96062b9 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayHttpClient.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayHttpClient.kt@@ -8,6 +8,8 @@ import kotlinx.coroutines.flow.asStateFlow import java.io.IOException import java.net.HttpURLConnection import java.net.URL+import java.util.concurrent.atomic.AtomicInteger+import kotlin.random.Random  /**  * Implementation of gplayapi's IHttpClient using HttpURLConnection.@@ -16,6 +18,14 @@ import java.net.URL  * Uses manual redirect handling (301-308, up to 5 hops) similar to  * library:network HttpUrlEngine, and ensures POST with empty body does not  * force an unwanted Content-Type.+ *+ * Requests are paced and a refusal is waited out rather than passed on. Play answers a+ * burst — "update all" across a phone's worth of Play apps is one purchase call and a+ * delivery per app — with 429, and the store used to hand that straight to the user as+ * "Failed: Too Many Requests" (issue #596). Pacing and backoff live here rather than at+ * each call site because the limit is on the account, not on any one feature: browse, the+ * update check and an install all spend from the same budget, and the background worker+ * runs in its own process-wide instance of the store's Play stack.  */ class PlayHttpClient : IHttpClient { @@ -23,6 +33,29 @@ class PlayHttpClient : IHttpClient {         private const val CONNECT_TIMEOUT = 30_000         private const val READ_TIMEOUT = 30_000         private const val MAX_REDIRECTS = 5++        private const val TOO_MANY_REQUESTS = 429+        private const val SERVICE_UNAVAILABLE = 503++        /** Smallest gap between two requests starting, before anything has been refused. */+        private const val MIN_REQUEST_GAP_MS = 250L+        private const val MAX_RETRIES = 3+        private const val BACKOFF_BASE_MS = 2_000L+        private const val BACKOFF_CEILING_MS = 30_000L++        /** Spread so several waiting callers don't all return at the same instant. */+        private const val BACKOFF_JITTER_MS = 500L++        private val pacingLock = Any()++        /** Earliest the next request may start. Shared: the limit is per account, not per client. */+        private var nextRequestAtMs = 0L++        private val waiting = AtomicInteger(0)+        private val _throttled = MutableStateFlow(false)++        /** True while any caller is sitting out a refusal, for a status line rather than an error. */+        val throttled: StateFlow<Boolean> = _throttled.asStateFlow()     }      private val _responseCode = MutableStateFlow(0)@@ -84,6 +117,9 @@ class PlayHttpClient : IHttpClient {         return execute(url, "POST", emptyMap(), body, contentType = "application/json")     } +    /** One attempt's answer, plus how long the server asked us to wait before the next. */+    private data class Attempt(val response: PlayResponse, val retryAfterMs: Long)+     private fun execute(         url: String,         method: String,@@ -91,6 +127,70 @@ class PlayHttpClient : IHttpClient {         rawBody: ByteArray?,         contentType: String? = null     ): PlayResponse {+        var attempt = 0+        while (true) {+            awaitTurn()+            val (response, retryAfterMs) = executeOnce(url, method, headers, rawBody, contentType)+            val refused = response.code == TOO_MANY_REQUESTS || response.code == SERVICE_UNAVAILABLE+            if (!refused || attempt >= MAX_RETRIES) return response+            backOff(attempt, retryAfterMs)+            attempt+++        }+    }++    /** Block until the shared pacing window opens, and claim it. */+    private fun awaitTurn() {+        val wait = synchronized(pacingLock) {+            val now = System.currentTimeMillis()+            val startAt = maxOf(now, nextRequestAtMs)+            nextRequestAtMs = startAt + MIN_REQUEST_GAP_MS+            startAt - now+        }+        if (wait > 0) sleep(wait)+    }++    /**+     * Wait out a refusal, and hold every other caller back for the same period — a limit+     * this request hit is one the next one would hit too.+     */+    private fun backOff(attempt: Int, retryAfterMs: Long) {+        val delay = (retryAfterMs.takeIf { it > 0 } ?: (BACKOFF_BASE_MS shl attempt))+            .coerceAtMost(BACKOFF_CEILING_MS)+        synchronized(pacingLock) {+            nextRequestAtMs = maxOf(nextRequestAtMs, System.currentTimeMillis() + delay)+        }+        waiting.incrementAndGet()+        _throttled.value = true+        try {+            sleep(delay + Random.nextLong(BACKOFF_JITTER_MS))+        } finally {+            _throttled.value = waiting.decrementAndGet() > 0+        }+    }++    private fun sleep(millis: Long) {+        try {+            Thread.sleep(millis)+        } catch (e: InterruptedException) {+            Thread.currentThread().interrupt()+            throw e+        }+    }++    /** `Retry-After` in milliseconds, or 0 when the server did not name a delay in seconds. */+    private fun retryAfterMs(conn: HttpURLConnection): Long =+        conn.getHeaderField("Retry-After")?.trim()?.toLongOrNull()+            ?.takeIf { it >= 0 }+            ?.times(1_000L)+            ?: 0L++    private fun executeOnce(+        url: String,+        method: String,+        headers: Map<String, String>,+        rawBody: ByteArray?,+        contentType: String? = null+    ): Attempt {         return try {             var currentUrl = url             var currentMethod = method@@ -98,7 +198,7 @@ class PlayHttpClient : IHttpClient {             var currentContentType: String? = contentType             var redirects = 0             var lastConn: HttpURLConnection? = null-            var result: PlayResponse? = null+            var result: Attempt? = null              while (result == null) {                 val conn = openConnection(currentUrl, currentMethod, headers, currentBody, currentContentType)@@ -129,6 +229,7 @@ class PlayHttpClient : IHttpClient {                  val ct = conn.getHeaderField("Content-Type")                 val responseMessage = try { conn.responseMessage } catch (_: Exception) { "" } ?: ""+                val retryAfter = retryAfterMs(conn)                 _responseCode.value = code                  val bytes = try {@@ -150,23 +251,29 @@ class PlayHttpClient : IHttpClient {                 val errBytes = if (!isSuccessful) bytes else ByteArray(0)                 val respBytes = if (isSuccessful) bytes else ByteArray(0) -                result = PlayResponse(-                    responseBytes = respBytes,-                    errorBytes = errBytes,-                    errorString = errStr,-                    isSuccessful = isSuccessful,-                    code = code,-                    type = ct+                result = Attempt(+                    PlayResponse(+                        responseBytes = respBytes,+                        errorBytes = errBytes,+                        errorString = errStr,+                        isSuccessful = isSuccessful,+                        code = code,+                        type = ct+                    ),+                    retryAfter,                 )             }             result         } catch (e: Exception) {-            PlayResponse(-                isSuccessful = false,-                code = -1,-                errorString = e.message ?: "Network error",-                errorBytes = ByteArray(0),-                responseBytes = ByteArray(0)+            Attempt(+                PlayResponse(+                    isSuccessful = false,+                    code = -1,+                    errorString = e.message ?: "Network error",+                    errorBytes = ByteArray(0),+                    responseBytes = ByteArray(0)+                ),+                0L,             )         }     }
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.ktindex db8d4b42fd..f9baec23c1 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt@@ -26,6 +26,7 @@ import com.vayunmathur.appstore.data.grapheneos.toUnifiedApp import com.vayunmathur.appstore.data.installer.InstallCoordinator import com.vayunmathur.appstore.data.installer.InstallStage import com.vayunmathur.appstore.data.play.PlayAuthState+import com.vayunmathur.appstore.data.play.PlayHttpClient import com.vayunmathur.appstore.data.play.PlayRepository import com.vayunmathur.appstore.data.priority import com.vayunmathur.appstore.data.searchCandidate@@ -157,6 +158,20 @@ class AppStoreViewModel(         RowChrome(installed, installed.map { it.packageName }.toSet(), icons, stages)     }.stateIn(viewModelScope, SharingStarted.Eagerly, RowChrome()) +    /**+     * The transient line under the top bar.+     *+     * Being rate-limited by Play outranks whatever else was being said, because it is the+     * reason nothing appears to be happening: the store is deliberately sitting still for+     * a few seconds rather than hammering an endpoint that has already refused it. Read+     * off the transport rather than the session — the limit is on the Play account and is+     * shared by every caller, including the background update worker's own stack.+     */+    private val statusLine: StateFlow<String> =+        combine(_statusMessage, PlayHttpClient.throttled) { message, throttled ->+            if (throttled) context.getString(R.string.play_rate_limited) else message+        }.stateIn(viewModelScope, SharingStarted.Eagerly, "")+     val updates: StateFlow<List<UnifiedApp>> = combine(         _catalogUpdates,         _playUpdates,@@ -203,7 +218,7 @@ class AppStoreViewModel(             updates,             _isSyncing,             _isLoadingHome,-            _statusMessage,+            statusLine,             _playError,         ) { u, syncing, loading, msg, playError ->             HomeChrome(u.size, syncing, loading, msg.ifBlank { playError })@@ -266,7 +281,7 @@ class AppStoreViewModel(         chrome,         _isCheckingUpdates,         _lastUpdateCheck,-        _statusMessage,+        statusLine,     ) { list, rows, checking, checkedAt, message ->         UpdatesUiState(             updates = list,
appstore/src/main/res/values/strings.xml
diff --git a/appstore/src/main/res/values/strings.xml b/appstore/src/main/res/values/strings.xmlindex b2d2ba5705..9c67e586be 100644--- a/appstore/src/main/res/values/strings.xml+++ b/appstore/src/main/res/values/strings.xml@@ -56,6 +56,8 @@     <!-- Message after tapping Sync sources with every source switched off. -->     <string name="sync_all_sources_off">Nothing to sync — every source is switched off.</string>     <string name="play_unavailable">Play Store results unavailable: %1$s</string>+    <!-- Status line under the top bar while the store is waiting out a Play Store rate limit. -->+    <string name="play_rate_limited">Play Store is limiting requests — waiting before trying again…</string>      <!-- Search. -->     <string name="search_placeholder">Search for an app</string>