Modern Apps git

← Modern-Apps.git

network: StaticMirror for R2-first reads with endpoint fallback (#static-r2)

Commit
d43cc1f7a2038373a7d843faf0c2112b811fa848
Author
Vayun Mathur <[email protected]>
When
2026-11-13 22:35 UTC (22 days ago)
Parents
bcd641f
The server (location_share_server, branch feat/static-r2) now publishes
every user-independent answer to a public Cloudflare R2 bucket served at
https://static.maproj.org: video-catalog shards, currency and eSIM rates,
the TMDB catalog and traffic squares. Apps that read those objects
directly stop costing the server a request per user, which is the
owner's goal ("constantify as many endpoints as possible through R2").

StaticMirror is the one shared policy for that:
- getStatic(url, maxAgeMs): the static object if it answered 2xx and,
  with maxAgeMs, carries a Last-Modified within that age; else null.
  For callers where a 200 is authoritative (a catalog shard that just
  lacks the item) or whose fallback is not a plain GET.
- get(staticUrl, fallbackUrl, maxAgeMs): static copy, else the old
  endpoint's response whatever its status.
- getJson: the same, decoded with NetworkClient's shared lenient JSON
  config; an undecodable static copy also falls back, and a failing
  fallback throws IOException("HTTP <status>: ...") like getJson.
Nothing changes before the bucket goes live: a missing object, an
unreachable host or a stale copy simply falls back to today's
endpoint. static.maproj.org is an R2 custom domain on the maproj.org
Cloudflare zone, so it is covered by the FIRST_PARTY pins like
api.maproj.org and data.maproj.org; no new trust.

A transport seam (internal var transport) keeps the tests hermetic.

Verified: StaticMirrorTest (static wins when present; 404, unreachable
and undecodable static copies fall back; Last-Modified age check
including a missing header; failing fallback throws HTTP 503;
getStatic returns only usable copies; RFC 1123 date parsing). Run with
:library:network:testDevUnitTest in the container build.

Diff

library/network/src/main/java/com/vayunmathur/library/network/StaticMirror.kt
diff --git a/library/network/src/main/java/com/vayunmathur/library/network/StaticMirror.kt b/library/network/src/main/java/com/vayunmathur/library/network/StaticMirror.ktnew file mode 100644index 0000000000..c1afb66112--- /dev/null+++ b/library/network/src/main/java/com/vayunmathur/library/network/StaticMirror.kt@@ -0,0 +1,94 @@+package com.vayunmathur.library.network++import java.time.ZonedDateTime+import java.time.format.DateTimeFormatter+import kotlinx.serialization.DeserializationStrategy+import kotlinx.serialization.serializer++/**+ * Static copies of user-independent server answers on Cloudflare R2.+ *+ * The server publishes everything whose answer is the same for every user —+ * video-catalog shards, rates, the TMDB catalog, traffic squares — to a public+ * bucket served at [BASE] (an R2 custom domain on the same Cloudflare zone as+ * `api.maproj.org`, so the `FIRST_PARTY` pins cover it). Apps read the static+ * object first and fall back to the old endpoint when it is missing, failing,+ * or older than they accept, so server cost stops growing with users and+ * nothing breaks before the bucket goes live (location_share_server+ * `src/static_r2`, `cloudflare/STATIC-R2.md`).+ */+object StaticMirror {+    /** Public origin of the static bucket. */+    const val BASE = "https://static.maproj.org"++    /** Test seam: when set, serves every request instead of [NetworkClient]. */+    internal var transport: (suspend (url: String) -> RawResponse)? = null++    private suspend fun fetch(url: String): RawResponse =+        transport?.invoke(url) ?: NetworkClient.execute(url)++    /**+     * The static object at [staticUrl] when it is usable ([accept]), else null —+     * for callers whose fallback is not a plain GET, or for whom a 200 is+     * authoritative (e.g. a catalog shard that simply lacks the item).+     */+    suspend fun getStatic(+        staticUrl: String,+        maxAgeMs: Long? = null,+        nowMs: Long = System.currentTimeMillis(),+    ): RawResponse? = runCatching { fetch(staticUrl) }.getOrNull()?.takeIf { accept(it, maxAgeMs, nowMs) }++    /**+     * GET [staticUrl]; when that throws, is not 2xx, or — with [maxAgeMs] — has no+     * `Last-Modified` within that age, GET [fallbackUrl] instead and return its+     * response whatever its status.+     */+    suspend fun get(+        staticUrl: String,+        fallbackUrl: String,+        maxAgeMs: Long? = null,+        nowMs: Long = System.currentTimeMillis(),+    ): RawResponse = getStatic(staticUrl, maxAgeMs, nowMs) ?: fetch(fallbackUrl)++    /**+     * [get] decoded as JSON with the shared lenient config. A static copy that+     * does not decode also falls back. A non-2xx fallback throws an+     * `IOException("HTTP <status>: ...")`, like [NetworkClient.getJson].+     */+    suspend fun <T> getJson(+        staticUrl: String,+        fallbackUrl: String,+        deserializer: DeserializationStrategy<T>,+        maxAgeMs: Long? = null,+        nowMs: Long = System.currentTimeMillis(),+    ): T {+        getStatic(staticUrl, maxAgeMs, nowMs)?.let { primary ->+            runCatching { NetworkClient.jsonConfig.decodeFromString(deserializer, primary.text) }+                .onSuccess { return it }+        }+        val resp = fetch(fallbackUrl)+        if (!resp.isSuccess) {+            throw java.io.IOException("HTTP ${resp.status}: ${resp.text.take(ERROR_PREFIX_CHARS)}")+        }+        return NetworkClient.jsonConfig.decodeFromString(deserializer, resp.text)+    }++    /** Reified [getJson]. */+    suspend inline fun <reified T> getJson(staticUrl: String, fallbackUrl: String, maxAgeMs: Long? = null): T =+        getJson(staticUrl, fallbackUrl, serializer<T>(), maxAgeMs)++    /** Whether a static response is usable: 2xx and, with [maxAgeMs], fresh enough. */+    fun accept(resp: RawResponse, maxAgeMs: Long?, nowMs: Long): Boolean {+        if (!resp.isSuccess) return false+        if (maxAgeMs == null) return true+        val modified = resp.header("Last-Modified")?.let(::parseHttpDate) ?: return false+        return nowMs - modified <= maxAgeMs+    }++    /** RFC 1123 HTTP date (`Fri, 13 Nov 2026 22:01:58 GMT`) to epoch millis, or null. */+    fun parseHttpDate(value: String): Long? = runCatching {+        ZonedDateTime.parse(value.trim(), DateTimeFormatter.RFC_1123_DATE_TIME).toInstant().toEpochMilli()+    }.getOrNull()++    private const val ERROR_PREFIX_CHARS = 200+}
library/network/src/test/java/com/vayunmathur/library/network/StaticMirrorTest.kt
diff --git a/library/network/src/test/java/com/vayunmathur/library/network/StaticMirrorTest.kt b/library/network/src/test/java/com/vayunmathur/library/network/StaticMirrorTest.ktnew file mode 100644index 0000000000..fa2020bb20--- /dev/null+++ b/library/network/src/test/java/com/vayunmathur/library/network/StaticMirrorTest.kt@@ -0,0 +1,95 @@+package com.vayunmathur.library.network++import kotlinx.coroutines.runBlocking+import kotlinx.serialization.Serializable+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Covers [StaticMirror]'s static-first / fallback policy through its transport seam. */+class StaticMirrorTest {++    @Serializable+    private data class Dto(val v: Int = 0)++    private val requested = mutableListOf<String>()++    private fun serve(vararg routes: Pair<String, RawResponse>) {+        val map = routes.toMap()+        StaticMirror.transport = { url ->+            requested += url+            map[url] ?: throw java.io.IOException("connect failed")+        }+    }++    private fun resp(status: Int, body: String, lastModified: String? = null) = RawResponse(+        status = status,+        statusMessage = "",+        bytes = body.toByteArray(),+        headers = lastModified?.let { mapOf("last-modified" to listOf(it)) } ?: emptyMap(),+        url = "",+    )++    @AfterTest+    fun reset() {+        StaticMirror.transport = null+    }++    private val now = StaticMirror.parseHttpDate("Fri, 13 Nov 2026 22:00:00 GMT")!!++    @Test+    fun static_copy_wins_when_present() = runBlocking {+        serve("s" to resp(200, """{"v":1}"""), "f" to resp(200, """{"v":2}"""))+        assertEquals(Dto(1), StaticMirror.getJson<Dto>("s", "f"))+        assertEquals(listOf("s"), requested)+    }++    @Test+    fun missing_failing_or_undecodable_static_copy_falls_back() = runBlocking {+        serve("s" to resp(404, "NoSuchKey"), "f" to resp(200, """{"v":2}"""))+        assertEquals(Dto(2), StaticMirror.getJson<Dto>("s", "f"))+        serve("f" to resp(200, """{"v":3}""")) // static host unreachable+        assertEquals(Dto(3), StaticMirror.getJson<Dto>("s", "f"))+        serve("s" to resp(200, "<html>"), "f" to resp(200, """{"v":4}"""))+        assertEquals(Dto(4), StaticMirror.getJson<Dto>("s", "f"))+    }++    @Test+    fun stale_static_copy_falls_back_fresh_one_is_used() = runBlocking {+        val hourAgo = "Fri, 13 Nov 2026 21:00:00 GMT"+        serve("s" to resp(200, "static", hourAgo), "f" to resp(200, "server"))+        assertEquals("static", StaticMirror.get("s", "f", maxAgeMs = 2 * 3_600_000L, nowMs = now).text)+        assertEquals("server", StaticMirror.get("s", "f", maxAgeMs = 600_000L, nowMs = now).text)+        // No Last-Modified at all: cannot prove freshness.+        serve("s" to resp(200, "static"), "f" to resp(200, "server"))+        assertEquals("server", StaticMirror.get("s", "f", maxAgeMs = 600_000L, nowMs = now).text)+        assertEquals("static", StaticMirror.get("s", "f", nowMs = now).text)+    }++    @Test+    fun failing_fallback_throws_like_getJson() {+        serve("s" to resp(404, ""), "f" to resp(503, "down"))+        val e = assertFailsWith<java.io.IOException> { runBlocking { StaticMirror.getJson<Dto>("s", "f") } }+        assertTrue(e.message!!.startsWith("HTTP 503"))+    }++    @Test+    fun get_static_returns_only_usable_copies() = runBlocking {+        serve("s" to resp(200, "[]"), "gone" to resp(404, ""))+        assertEquals("[]", StaticMirror.getStatic("s")?.text)+        assertNull(StaticMirror.getStatic("gone"))+        assertNull(StaticMirror.getStatic("unreachable"))+        assertNull(StaticMirror.getStatic("s", maxAgeMs = 1000L, nowMs = now), "no Last-Modified")+    }++    @Test+    fun http_dates_parse() {+        assertEquals(1794607200000L, now)+        assertNull(StaticMirror.parseHttpDate("yesterday"))+        assertFalse(StaticMirror.accept(resp(500, ""), null, now))+    }+}