network: central opt-in retry with idempotency gating
- Commit
a22d63c35d7dfe5b77e05b8f758da298bfb6a76b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 11:57 UTC (14 days ago)
- Parents
c47150f
Every app hand-rolled its own retry loop or had none. NetworkClient now offers executeWithRetry/ performRequestWithRetry: GET/HEAD/PUT/DELETE retry on 408/429/502/503/504 and IOExceptions with capped exponential backoff plus jitter; other methods run exactly once unless the caller passes an idempotency key, sent as the Idempotency-Key header on every attempt. Retry-After is honoured in both seconds and HTTP-date forms via one shared parser - appstore's Play parser moved into library/network and now delegates. Travel's polling transport is the first migrant; WebSocket reconnects, the Play pacing loop and the range-resume downloader deliberately stay as they are (documented in the change). Verified: 13 new retry/parser tests pass; travel and appstore compile and their retry tests stay green.
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 4e0525f0a0..1798d421fb 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@@ -5,13 +5,10 @@ import com.aurora.gplayapi.network.IHttpClient import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow+import com.vayunmathur.library.network.RetryAfter import java.io.IOException import java.net.HttpURLConnection import java.net.URL-import java.time.DateTimeException-import java.time.ZonedDateTime-import java.time.format.DateTimeFormatter-import java.util.Locale import java.util.concurrent.atomic.AtomicInteger import kotlin.random.Random @@ -43,7 +40,6 @@ class PlayHttpClient : IHttpClient { private const val TOO_MANY_REQUESTS = 429 private const val SERVICE_UNAVAILABLE = 503- private const val MILLIS_PER_SECOND = 1_000L private const val NETWORK_FAILURE_CODE = -1 /** Smallest gap between two requests starting, before anything has been refused. */@@ -78,50 +74,14 @@ class PlayHttpClient : IHttpClient { _throttled.value = false } - /** RFC 850 (obsolete) HTTP-date, e.g. `Sunday, 06-Nov-94 08:49:37 GMT`. */- private val RFC_850_FORMAT: DateTimeFormatter =- DateTimeFormatter.ofPattern("EEEE, dd-MMM-yy HH:mm:ss z", Locale.US)-- /** ANSI C asctime (obsolete) HTTP-date, e.g. `Sun Nov 6 08:49:37 1994` (GMT assumed). */- private val ASCTIME_FORMAT: DateTimeFormatter =- DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss yyyy", Locale.US)- /** * Parses a `Retry-After` header value (RFC 9110 §10.2.3) to milliseconds- * from [nowMs]: either delay-seconds (`120`) or an HTTP-date- * (`Sun, 06 Nov 1994 08:49:37 GMT`, in any of the three formats a- * recipient must accept). A date in the past, an absent header and an- * unparseable value all yield 0, which the caller reads as "no server- * delay named" and falls back to exponential backoff for.+ * from [nowMs]. Delegates to [RetryAfter], the repo's one parser in+ * `:library:network`; kept under this name for the pacing call site+ * and its tests. See [RetryAfter.parseMs] for the exact contract. */- internal fun parseRetryAfterMs(header: String?, nowMs: Long = System.currentTimeMillis()): Long {- val value = header?.trim()?.takeIf { it.isNotEmpty() } ?: return 0L- value.toLongOrNull()?.let { seconds ->- return if (seconds >= 0) seconds * MILLIS_PER_SECOND else 0L- }- val dateMs = parseHttpDateMs(value) ?: return 0L- return (dateMs - nowMs).coerceAtLeast(0L)- }-- private fun parseHttpDateMs(value: String): Long? {- // Collapse runs of spaces: asctime pads a single-digit day with one.- val normalized = value.replace(Regex(" +"), " ")- val formatters = listOf(DateTimeFormatter.RFC_1123_DATE_TIME, RFC_850_FORMAT, ASCTIME_FORMAT)- for (formatter in formatters) {- try {- return ZonedDateTime.parse(normalized, formatter).toInstant().toEpochMilli()- } catch (_: DateTimeException) {- // Try the next sanctioned format.- }- }- // asctime carries no zone; RFC 9110 dates are GMT, so retry it as UTC.- return try {- java.time.LocalDateTime.parse(normalized, ASCTIME_FORMAT)- .toInstant(java.time.ZoneOffset.UTC).toEpochMilli()- } catch (_: DateTimeException) {- null- }- }+ internal fun parseRetryAfterMs(header: String?, nowMs: Long = System.currentTimeMillis()): Long =+ RetryAfter.parseMs(header, nowMs) } /**
library/network/src/main/java/com/vayunmathur/library/network/NetworkRetry.kt
diff --git a/library/network/src/main/java/com/vayunmathur/library/network/NetworkRetry.kt b/library/network/src/main/java/com/vayunmathur/library/network/NetworkRetry.ktnew file mode 100644index 0000000000..56d5337e4f--- /dev/null+++ b/library/network/src/main/java/com/vayunmathur/library/network/NetworkRetry.kt@@ -0,0 +1,193 @@+package com.vayunmathur.library.network++import java.io.IOException+import javax.net.ssl.SSLSocketFactory+import kotlin.random.Random+import kotlinx.coroutines.delay++/**+ * Central, opt-in retry for [NetworkClient] — the only retry loop app+ * `network.Networking` owners should need for a single HTTP request.+ *+ * Policy in one paragraph: idempotent methods (GET/HEAD/PUT/DELETE) are+ * retried on 408/429/502/503/504 and on [IOException]; any other method is+ * retried only when the caller passes an idempotency key, which is sent as+ * the `Idempotency-Key` header on every attempt so the server can dedupe.+ * The wait between attempts honours `Retry-After` (both forms, via+ * [RetryAfter]) and otherwise doubles from [RetryPolicy.initialDelayMs],+ * capped at [RetryPolicy.maxDelayMs], plus jitter so throttled clients do+ * not retry in lockstep. After the last attempt the final response is+ * returned (status failures never throw, matching [NetworkClient.execute])+ * or the final [IOException] is rethrown.+ *+ * Business polling — "keep asking until the job finishes" (travel pricing,+ * order status) — is NOT this: those loops stay in their app and only their+ * per-request transient failure handling moves here.+ */+data class RetryPolicy(+ /** Total attempts including the first; 1 disables retry. */+ val maxAttempts: Int = DEFAULT_MAX_ATTEMPTS,+ /** First backoff step; doubles per attempt. */+ val initialDelayMs: Long = DEFAULT_INITIAL_DELAY_MS,+ /** Cap for both backoff and a server-named `Retry-After`. */+ val maxDelayMs: Long = DEFAULT_MAX_DELAY_MS,+ /** Uniform jitter added to each wait, in `[0, jitterMs)`. */+ val jitterMs: Long = DEFAULT_JITTER_MS,+ /** Statuses worth another attempt. */+ val retryableStatuses: Set<Int> = RETRYABLE_STATUSES,+) {+ init {+ require(maxAttempts >= 1) { "maxAttempts must be >= 1" }+ require(initialDelayMs >= 0 && maxDelayMs >= 0 && jitterMs >= 0) { "delays must be >= 0" }+ }++ companion object {+ const val DEFAULT_MAX_ATTEMPTS = 3+ const val DEFAULT_INITIAL_DELAY_MS = 500L+ const val DEFAULT_MAX_DELAY_MS = 30_000L+ const val DEFAULT_JITTER_MS = 250L++ /** Transient statuses: request timeout, throttling, gateway/server overload. */+ val RETRYABLE_STATUSES: Set<Int> = setOf(408, 429, 502, 503, 504)++ val DEFAULT = RetryPolicy()+ val NONE = RetryPolicy(maxAttempts = 1)+ }+}++/** Methods that are safe to replay verbatim (RFC 9110 §9.2.2). */+private val IDEMPOTENT_METHODS = setOf("GET", "HEAD", "PUT", "DELETE")++internal const val IDEMPOTENCY_KEY_HEADER = "Idempotency-Key"+internal const val RETRY_AFTER_HEADER = "Retry-After"++/** True when [method] may be replayed under [idempotencyKey] (null = no key supplied). */+internal fun isRetryEligible(method: String, idempotencyKey: String?): Boolean =+ method.uppercase() in IDEMPOTENT_METHODS || !idempotencyKey.isNullOrBlank()++/**+ * Wait before attempt [attempt] (0-based failure count): the server-named+ * [retryAfterMs] when positive, else exponential backoff; both capped at+ * [RetryPolicy.maxDelayMs], plus jitter.+ */+internal fun retryDelayMs(+ policy: RetryPolicy,+ attempt: Int,+ retryAfterMs: Long,+ random: Random = Random,+): Long {+ val base = if (retryAfterMs > 0) {+ retryAfterMs+ } else {+ val shift = attempt.coerceIn(0, MAX_BACKOFF_SHIFT)+ (policy.initialDelayMs shl shift)+ }+ val capped = base.coerceIn(0, policy.maxDelayMs)+ val jitter = if (policy.jitterMs > 0) random.nextLong(policy.jitterMs) else 0L+ return capped + jitter+}++private const val MAX_BACKOFF_SHIFT = 10++/**+ * Runs [block] until it yields a non-retryable result, throws a+ * non-[IOException], or [RetryPolicy.maxAttempts] is exhausted.+ *+ * [shouldRetry] decides whether a result is transient; [retryAfterMsOf]+ * extracts the server-named wait from a result (0 = none named). The wait+ * itself goes through [sleeper] so tests can record instead of sleeping.+ * Cancellation is never swallowed: `delay` (the default sleeper) and+ * [block] both propagate it, and it is not an [IOException].+ */+suspend fun <T> withRetry(+ policy: RetryPolicy = RetryPolicy.DEFAULT,+ shouldRetry: (T) -> Boolean,+ retryAfterMsOf: (T) -> Long = { 0L },+ sleeper: suspend (Long) -> Unit = { delay(it) },+ block: suspend () -> T,+): T {+ var attempt = 0+ while (true) {+ val result = try {+ block()+ } catch (e: IOException) {+ if (attempt >= policy.maxAttempts - 1) throw e+ sleeper(retryDelayMs(policy, attempt, retryAfterMs = 0L))+ attempt+++ continue+ }+ if (!shouldRetry(result) || attempt >= policy.maxAttempts - 1) return result+ sleeper(retryDelayMs(policy, attempt, retryAfterMsOf(result)))+ attempt+++ }+}++/** Adds the `Idempotency-Key` header unless the caller already set one. */+private fun withIdempotencyKey(+ headers: Map<String, *>,+ idempotencyKey: String?,+): Map<String, Any?> {+ if (idempotencyKey.isNullOrBlank()) return headers.mapValues { it.value }+ val hasKey = headers.keys.any { it.equals(IDEMPOTENCY_KEY_HEADER, ignoreCase = true) }+ if (hasKey) return headers.mapValues { it.value }+ return headers.mapValues { it.value } + (IDEMPOTENCY_KEY_HEADER to idempotencyKey)+}++/**+ * [NetworkClient.execute] with central retry (see [RetryPolicy]). Opt-in:+ * plain `execute` never retries. A non-idempotent method without+ * [idempotencyKey] is executed exactly once, whatever the policy says.+ */+suspend fun NetworkClient.executeWithRetry(+ url: String,+ method: String = "GET",+ headers: Map<String, *> = emptyMap<String, Any>(),+ body: Any? = null,+ followRedirects: Boolean = true,+ connectTimeoutMs: Long? = null,+ readTimeoutMs: Long? = connectTimeoutMs,+ sslSocketFactory: SSLSocketFactory? = null,+ useSystemTrust: Boolean = false,+ retryPolicy: RetryPolicy = RetryPolicy.DEFAULT,+ idempotencyKey: String? = null,+): RawResponse {+ if (!isRetryEligible(method, idempotencyKey)) {+ return execute(url, method, headers, body, followRedirects, connectTimeoutMs, readTimeoutMs, sslSocketFactory, useSystemTrust)+ }+ val attemptHeaders = withIdempotencyKey(headers, idempotencyKey)+ return withRetry(+ policy = retryPolicy,+ shouldRetry = { it.status in retryPolicy.retryableStatuses },+ retryAfterMsOf = { RetryAfter.parseMs(it.header(RETRY_AFTER_HEADER)) },+ ) {+ execute(url, method, attemptHeaders, body, followRedirects, connectTimeoutMs, readTimeoutMs, sslSocketFactory, useSystemTrust)+ }+}++/**+ * [NetworkClient.performRequest] with central retry; same contract as+ * [executeWithRetry]. Exists because `performRequest` (HttpURLConnection,+ * text body) is the shape most app `Networking` owners already call.+ */+suspend fun NetworkClient.performRequestWithRetry(+ url: String,+ method: String = "GET",+ headers: Map<String, *> = emptyMap<String, Any>(),+ body: Any? = null,+ sslSocketFactory: SSLSocketFactory? = null,+ useSystemTrust: Boolean = false,+ retryPolicy: RetryPolicy = RetryPolicy.DEFAULT,+ idempotencyKey: String? = null,+): SimpleResponse {+ if (!isRetryEligible(method, idempotencyKey)) {+ return performRequest(url, method, headers, body, sslSocketFactory, useSystemTrust)+ }+ val attemptHeaders = withIdempotencyKey(headers, idempotencyKey)+ return withRetry(+ policy = retryPolicy,+ shouldRetry = { it.status in retryPolicy.retryableStatuses },+ retryAfterMsOf = { RetryAfter.parseMs(it.header(RETRY_AFTER_HEADER)) },+ ) {+ performRequest(url, method, attemptHeaders, body, sslSocketFactory, useSystemTrust)+ }+}
library/network/src/main/java/com/vayunmathur/library/network/RetryAfter.kt
diff --git a/library/network/src/main/java/com/vayunmathur/library/network/RetryAfter.kt b/library/network/src/main/java/com/vayunmathur/library/network/RetryAfter.ktnew file mode 100644index 0000000000..fd77ba86a4--- /dev/null+++ b/library/network/src/main/java/com/vayunmathur/library/network/RetryAfter.kt@@ -0,0 +1,65 @@+package com.vayunmathur.library.network++import java.time.DateTimeException+import java.time.LocalDateTime+import java.time.ZoneOffset+import java.time.ZonedDateTime+import java.time.format.DateTimeFormatter+import java.util.Locale++/**+ * The one `Retry-After` parser for the repo (RFC 9110 §10.2.3).+ *+ * Moved here from appstore's `PlayHttpClient` so every retry path reads the+ * header the same way; appstore delegates to this instead of keeping a second+ * parser, and nothing else should grow a third.+ */+object RetryAfter {++ private const val MILLIS_PER_SECOND = 1_000L++ /** RFC 850 (obsolete) HTTP-date, e.g. `Sunday, 06-Nov-94 08:49:37 GMT`. */+ private val RFC_850_FORMAT: DateTimeFormatter =+ DateTimeFormatter.ofPattern("EEEE, dd-MMM-yy HH:mm:ss z", Locale.US)++ /** ANSI C asctime (obsolete) HTTP-date, e.g. `Sun Nov 6 08:49:37 1994` (GMT assumed). */+ private val ASCTIME_FORMAT: DateTimeFormatter =+ DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss yyyy", Locale.US)++ /**+ * Parses a `Retry-After` header value to milliseconds from [nowMs]:+ * either delay-seconds (`120`) or an HTTP-date+ * (`Sun, 06 Nov 1994 08:49:37 GMT`, in any of the three formats a+ * recipient must accept). A date in the past, an absent header and an+ * unparseable value all yield 0, which the caller reads as "no server+ * delay named" and falls back to exponential backoff for.+ */+ fun parseMs(header: String?, nowMs: Long = System.currentTimeMillis()): Long {+ val value = header?.trim()?.takeIf { it.isNotEmpty() } ?: return 0L+ value.toLongOrNull()?.let { seconds ->+ return if (seconds >= 0) seconds * MILLIS_PER_SECOND else 0L+ }+ val dateMs = parseHttpDateMs(value) ?: return 0L+ return (dateMs - nowMs).coerceAtLeast(0L)+ }++ private fun parseHttpDateMs(value: String): Long? {+ // Collapse runs of spaces: asctime pads a single-digit day with one.+ val normalized = value.replace(Regex(" +"), " ")+ val formatters = listOf(DateTimeFormatter.RFC_1123_DATE_TIME, RFC_850_FORMAT, ASCTIME_FORMAT)+ for (formatter in formatters) {+ try {+ return ZonedDateTime.parse(normalized, formatter).toInstant().toEpochMilli()+ } catch (_: DateTimeException) {+ // Try the next sanctioned format.+ }+ }+ // asctime carries no zone; RFC 9110 dates are GMT, so retry it as UTC.+ return try {+ LocalDateTime.parse(normalized, ASCTIME_FORMAT)+ .toInstant(ZoneOffset.UTC).toEpochMilli()+ } catch (_: DateTimeException) {+ null+ }+ }+}
library/network/src/test/java/com/vayunmathur/library/network/NetworkRetryTest.kt
diff --git a/library/network/src/test/java/com/vayunmathur/library/network/NetworkRetryTest.kt b/library/network/src/test/java/com/vayunmathur/library/network/NetworkRetryTest.ktnew file mode 100644index 0000000000..036c92d966--- /dev/null+++ b/library/network/src/test/java/com/vayunmathur/library/network/NetworkRetryTest.kt@@ -0,0 +1,221 @@+package com.vayunmathur.library.network++import com.sun.net.httpserver.HttpServer+import java.io.IOException+import java.net.InetSocketAddress+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.assertFailsWith+import kotlinx.coroutines.runBlocking++/**+ * Central retry (NetworkRetry): status/IOException retry, idempotency gate,+ * `Retry-After` handling and give-up. Backoff logic runs through [withRetry]+ * with a recording sleeper (no wall-clock waits); the [NetworkClient]+ * wrappers run against a local server like the other engine tests.+ */+class NetworkRetryTest {++ private lateinit var server: HttpServer+ private var baseUrl = ""++ /** Deterministic policy: no jitter, no real delay at the wrapper level. */+ private val fastPolicy = RetryPolicy(+ maxAttempts = 3,+ initialDelayMs = 1L,+ maxDelayMs = 10L,+ jitterMs = 0L,+ )++ @BeforeTest+ fun setUp() {+ server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+ baseUrl = "http://127.0.0.1:${server.address.port}"+ server.start()+ }++ @AfterTest+ fun tearDown() {+ server.stop(0)+ }++ private fun response(status: Int, retryAfter: String? = null): RawResponse {+ val headers = if (retryAfter == null) {+ emptyMap()+ } else {+ mapOf(RETRY_AFTER_HEADER to listOf(retryAfter))+ }+ return RawResponse(status, "", ByteArray(0), headers, "http://localhost/")+ }++ @Test+ fun retries_on_503_then_succeeds() = runBlocking {+ val sleeps = mutableListOf<Long>()+ var calls = 0+ val result = withRetry(+ policy = fastPolicy,+ shouldRetry = { it.status in fastPolicy.retryableStatuses },+ retryAfterMsOf = { RetryAfter.parseMs(it.header(RETRY_AFTER_HEADER)) },+ sleeper = { sleeps.add(it) },+ ) {+ calls+++ if (calls < 3) response(503) else response(200)+ }+ assertEquals(200, result.status)+ assertEquals(3, calls)+ assertEquals(2, sleeps.size)+ }++ @Test+ fun retry_after_header_is_honoured_over_backoff() = runBlocking {+ val sleeps = mutableListOf<Long>()+ var calls = 0+ val policy = RetryPolicy(maxAttempts = 3, initialDelayMs = 1L, maxDelayMs = 60_000L, jitterMs = 0L)+ val result = withRetry(+ policy = policy,+ shouldRetry = { it.status == 429 },+ retryAfterMsOf = { RetryAfter.parseMs(it.header(RETRY_AFTER_HEADER)) },+ sleeper = { sleeps.add(it) },+ ) {+ calls+++ if (calls == 1) response(429, retryAfter = "2") else response(200)+ }+ assertEquals(200, result.status)+ assertEquals(listOf(2_000L), sleeps)+ }++ @Test+ fun gives_up_after_max_attempts_and_returns_last_response() = runBlocking {+ var calls = 0+ val result = withRetry(+ policy = fastPolicy,+ shouldRetry = { it.status == 503 },+ sleeper = { },+ ) {+ calls+++ response(503)+ }+ assertEquals(503, result.status)+ assertEquals(fastPolicy.maxAttempts, calls)+ }++ @Test+ fun gives_up_after_max_attempts_and_rethrows_ioexception() = runBlocking {+ var calls = 0+ assertFailsWith<IOException> {+ withRetry<RawResponse>(+ policy = fastPolicy,+ shouldRetry = { false },+ sleeper = { },+ ) {+ calls+++ throw IOException("boom $calls")+ }+ }+ assertEquals(fastPolicy.maxAttempts, calls)+ }++ @Test+ fun non_retryable_status_is_returned_immediately() = runBlocking {+ var calls = 0+ val result = withRetry(+ policy = fastPolicy,+ shouldRetry = { it.status in fastPolicy.retryableStatuses },+ sleeper = { },+ ) {+ calls+++ response(404)+ }+ assertEquals(404, result.status)+ assertEquals(1, calls)+ }++ @Test+ fun executeWithRetry_retries_get_on_503_then_succeeds() = runBlocking {+ val hits = AtomicInteger()+ server.createContext("/flaky") { exchange ->+ val n = hits.incrementAndGet()+ if (n < 3) {+ exchange.sendResponseHeaders(503, -1)+ } else {+ val body = "ok".toByteArray()+ exchange.sendResponseHeaders(200, body.size.toLong())+ exchange.responseBody.use { it.write(body) }+ }+ exchange.close()+ }+ val result = NetworkClient.executeWithRetry("$baseUrl/flaky", retryPolicy = fastPolicy)+ assertEquals(200, result.status)+ assertEquals("ok", result.text)+ assertEquals(3, hits.get())+ }++ @Test+ fun executeWithRetry_does_not_retry_post_without_idempotency_key() = runBlocking {+ val hits = AtomicInteger()+ server.createContext("/submit") { exchange ->+ hits.incrementAndGet()+ exchange.requestBody.use { it.readBytes() }+ exchange.sendResponseHeaders(503, -1)+ exchange.close()+ }+ val result = NetworkClient.executeWithRetry(+ "$baseUrl/submit",+ method = "POST",+ body = "payload",+ retryPolicy = fastPolicy,+ )+ assertEquals(503, result.status)+ assertEquals(1, hits.get())+ }++ @Test+ fun executeWithRetry_retries_post_with_idempotency_key_and_sends_header() = runBlocking {+ val hits = AtomicInteger()+ val seenKeys = mutableListOf<String?>()+ server.createContext("/submit-keyed") { exchange ->+ val n = hits.incrementAndGet()+ synchronized(seenKeys) { seenKeys.add(exchange.requestHeaders.getFirst(IDEMPOTENCY_KEY_HEADER)) }+ exchange.requestBody.use { it.readBytes() }+ if (n < 2) {+ exchange.sendResponseHeaders(503, -1)+ } else {+ exchange.sendResponseHeaders(200, -1)+ }+ exchange.close()+ }+ val result = NetworkClient.executeWithRetry(+ "$baseUrl/submit-keyed",+ method = "POST",+ body = "payload",+ retryPolicy = fastPolicy,+ idempotencyKey = "booking-123",+ )+ assertEquals(200, result.status)+ assertEquals(2, hits.get())+ assertEquals(listOf<String?>("booking-123", "booking-123"), synchronized(seenKeys) { seenKeys.toList() })+ }++ @Test+ fun performRequestWithRetry_retries_get_on_503_then_succeeds() = runBlocking {+ val hits = AtomicInteger()+ server.createContext("/flaky-text") { exchange ->+ val n = hits.incrementAndGet()+ if (n < 2) {+ exchange.sendResponseHeaders(503, -1)+ } else {+ val body = "ok".toByteArray()+ exchange.sendResponseHeaders(200, body.size.toLong())+ exchange.responseBody.use { it.write(body) }+ }+ exchange.close()+ }+ val result = NetworkClient.performRequestWithRetry("$baseUrl/flaky-text", retryPolicy = fastPolicy)+ assertEquals(200, result.status)+ assertEquals("ok", result.body)+ assertEquals(2, hits.get())+ }+}
library/network/src/test/java/com/vayunmathur/library/network/RetryAfterTest.kt
diff --git a/library/network/src/test/java/com/vayunmathur/library/network/RetryAfterTest.kt b/library/network/src/test/java/com/vayunmathur/library/network/RetryAfterTest.ktnew file mode 100644index 0000000000..83f41f332f--- /dev/null+++ b/library/network/src/test/java/com/vayunmathur/library/network/RetryAfterTest.kt@@ -0,0 +1,49 @@+package com.vayunmathur.library.network++import java.time.ZoneOffset+import java.time.ZonedDateTime+import java.time.format.DateTimeFormatter+import kotlin.test.Test+import kotlin.test.assertEquals++/** Pure `Retry-After` parsing (RFC 9110): delay-seconds and HTTP-date forms. */+class RetryAfterTest {++ // Sun, 06 Nov 1994 08:49:37 GMT — the RFC's own example instant.+ private val exampleMs = ZonedDateTime.of(1994, 11, 6, 8, 49, 37, 0, ZoneOffset.UTC)+ .toInstant().toEpochMilli()++ @Test+ fun delay_seconds_parse_to_millis() {+ assertEquals(0L, RetryAfter.parseMs("0", nowMs = 1_000L))+ assertEquals(120_000L, RetryAfter.parseMs("120", nowMs = 1_000L))+ assertEquals(5_000L, RetryAfter.parseMs(" 5 ", nowMs = 1_000L))+ }++ @Test+ fun imf_fixdate_parses_relative_to_now() {+ val header = DateTimeFormatter.RFC_1123_DATE_TIME.format(+ ZonedDateTime.ofInstant(java.time.Instant.ofEpochMilli(exampleMs), ZoneOffset.UTC),+ )+ assertEquals(37_000L, RetryAfter.parseMs(header, nowMs = exampleMs - 37_000L))+ assertEquals(+ 37_000L,+ RetryAfter.parseMs("Sun, 06 Nov 1994 08:49:37 GMT", nowMs = exampleMs - 37_000L),+ )+ }++ @Test+ fun past_http_date_and_garbage_yield_zero() {+ assertEquals(0L, RetryAfter.parseMs("Sun, 06 Nov 1994 08:49:37 GMT", nowMs = exampleMs + 1))+ assertEquals(0L, RetryAfter.parseMs("soon", nowMs = 0L))+ assertEquals(0L, RetryAfter.parseMs(null, nowMs = 0L))+ assertEquals(0L, RetryAfter.parseMs("", nowMs = 0L))+ assertEquals(0L, RetryAfter.parseMs("-5", nowMs = 0L))+ }++ @Test+ fun asctime_form_parses_as_gmt() {+ // Sun Nov 6 08:49:37 1994 — same instant, obsolete asctime form.+ assertEquals(10_000L, RetryAfter.parseMs("Sun Nov 6 08:49:37 1994", nowMs = exampleMs - 10_000L))+ }+}
travel/src/main/java/com/vayunmathur/travel/network/TravelApiCore.kt
diff --git a/travel/src/main/java/com/vayunmathur/travel/network/TravelApiCore.kt b/travel/src/main/java/com/vayunmathur/travel/network/TravelApiCore.ktindex 0bce24e1ca..ef2fbe9a03 100644--- a/travel/src/main/java/com/vayunmathur/travel/network/TravelApiCore.kt+++ b/travel/src/main/java/com/vayunmathur/travel/network/TravelApiCore.kt@@ -1,6 +1,7 @@ package com.vayunmathur.travel.network import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.performRequestWithRetry import java.net.URLEncoder import kotlinx.serialization.json.Json import kotlinx.serialization.json.jsonArray@@ -107,7 +108,16 @@ internal var travelTransport: (suspend (method: String, url: String, body: Strin internal suspend fun travelPerform(method: String, url: String, body: String? = null): TravelRaw { travelTransport?.let { return it(method, url, body) }- val res = if (body == null) {+ // GETs go through the central retry (library:network NetworkRetry): the+ // pollers below (trip status, ancillaries-pricing, cancellation/change+ // status) used to spend a whole poll round on a transient 503/IOException;+ // that tolerance now lives in one place with backoff + Retry-After.+ // POSTs stay single-attempt — no idempotency keys in this protocol, so+ // checkout/confirm are never replayed. Business polling (waiting for+ // pricing/status to change) remains in the ViewModel ops, unchanged.+ val res = if (method == "GET" && body == null) {+ NetworkClient.performRequestWithRetry(url = url, method = method)+ } else if (body == null) { NetworkClient.performRequest(url = url, method = method) } else { NetworkClient.performRequest(