Modern Apps git

← Modern-Apps.git

weather: fetch weather from static R2 tiles, API as fallback (#weather-r2)

Commit
0fcb3072e18b3e3c1d518ad20e74e30fd696244e
Author
Vayun Mathur <[email protected]>
When
2026-11-13 23:30 UTC (22 days ago)
Parents
cd1644b
What: WeatherApi.bundle() (full bundles: home screen, refresh worker,
assistant intents) now gets weather from static files on Cloudflare R2
(https://static.maproj.org/wx/v1/, bucket `static`) and computes the
bundle on device; any failure falls back to the existing
/wx/v1/bundle API, which is unchanged, so the rollout is safe and old
app versions keep working.

Why: server weather cost must stop growing with users. With this, a
user's refreshes cost the server nothing; R2 serves fixed-size static
objects (no API responses are edge-cached).

How (network/WxStatic):
- latest.json names the current export run, the tiling and when the
  next model run is due (next_check). It is re-read only after
  next_check (and at most every 15 min, or when 12 h old), so the
  hourly WeatherRefreshWorker usually makes zero requests: the bundle
  is recomputed locally for the new hour from cached tiles.
- A new run costs one GET per location tile (~1°×1°; measured on a
  full-globe export: mean 37 KB, p50 39 KB, p90 58 KB, max 76 KB;
  European tiles ~50 KB); finished days live in immutable per-day
  history objects (mean 5.2 KB, one new per day); the point's geo block
  (elevation + time zone, ~4.6 KB) is fetched once ever. All cached on
  disk under cacheDir by run id; old runs/days are deleted.
- Ocean points (no tile) get a cached NotCovered for the run and use
  the API; so do clock-skewed clients and any decode/format error.
- FIRST_PARTY trust covers static.maproj.org (Cloudflare custom domain;
  verify its certificate chain before turning the bucket on).
- WxStatic.init(context) from MainActivity and the refresh worker.
Search-result temperatures (/wx/v1/current) and the map's tz lookup
(fields=tz) stay on the API: they are small, cheap requests.

Also fixes WxParityTest's JSON encoder (encodeDefaults, so v/model/step
compare) and the detekt findings in the new code (named HTTP/time
constants, documented NotCovered, smaller diff helper).

Verified: WxStaticTest drives WxStatic against the fixture objects with
a fake fetcher: first bundle = latest.json + tile + history days + geo
block, the same run an hour later = 0 requests, after next_check =
latest.json only, an ocean point = NotCovered with one tile request
for the run. WxParityTest (previous commit) covers the computation.
Device testing was out of scope for this task.

Diff

weather/src/main/java/com/vayunmathur/weather/MainActivity.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt b/weather/src/main/java/com/vayunmathur/weather/MainActivity.ktindex 61067c6f52..e0ae395c13 100644--- a/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt+++ b/weather/src/main/java/com/vayunmathur/weather/MainActivity.kt@@ -10,6 +10,7 @@ import com.vayunmathur.library.util.OfflineAware import com.vayunmathur.library.widgets.updateWidgetPreviews import com.vayunmathur.weather.data.GeoDatabase import com.vayunmathur.weather.data.WeatherRepository+import com.vayunmathur.weather.network.WxStatic import com.vayunmathur.weather.platform.WeatherViewModel import com.vayunmathur.weather.platform.WeatherViewModelFactory import com.vayunmathur.weather.widget.glance.WeatherGlanceWidgetReceiver@@ -21,8 +22,12 @@ class MainActivity : MaActivity() {      override fun onCreateBeforeContent() {         // FIRST_PARTY covers api.maproj.org (self-hosted weather bundle-        // and tiles proxy — place search is a committed on-device asset).+        // fallback and tiles proxy) and static.maproj.org (static weather+        // tiles, R2 custom domain on the same Cloudflare roots); place+        // search is a committed on-device asset.         NetworkClient.init(this, TrustBundle.FIRST_PARTY)+        // Static weather tiles (static.maproj.org), cached under cacheDir.+        WxStatic.init(this)         GeoDatabase.init(this)         // Unpacking is a ~13 MB brotli decompression and disk write. Do it now,         // in the background, rather than the first time the user opens search.
weather/src/main/java/com/vayunmathur/weather/data/WeatherRefreshWorker.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/data/WeatherRefreshWorker.kt b/weather/src/main/java/com/vayunmathur/weather/data/WeatherRefreshWorker.ktindex 5321a9af18..37f207a366 100644--- a/weather/src/main/java/com/vayunmathur/weather/data/WeatherRefreshWorker.kt+++ b/weather/src/main/java/com/vayunmathur/weather/data/WeatherRefreshWorker.kt@@ -11,6 +11,7 @@ import androidx.work.WorkerParameters import com.vayunmathur.weather.widget.glance.WeatherBlobGlanceWidget import com.vayunmathur.weather.widget.glance.WeatherGlanceWidget import com.vayunmathur.weather.network.WeatherApi+import com.vayunmathur.weather.network.WxStatic import com.vayunmathur.weather.network.toAirQuality import com.vayunmathur.weather.network.toForecastResponse import java.util.concurrent.TimeUnit@@ -26,6 +27,7 @@ class WeatherRefreshWorker(     override suspend fun doWork(): Result {         return try {             val repo = WeatherRepository.get(context)+            WxStatic.init(context)             val locations = repo.getLocations()             for (location in locations) {                 try {
weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt b/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.ktindex c25b342097..b156acc32f 100644--- a/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt+++ b/weather/src/main/java/com/vayunmathur/weather/network/WeatherApi.kt@@ -1,5 +1,6 @@ package com.vayunmathur.weather.network +import com.vayunmathur.library.log.Log import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.weather.data.GeoDatabase @@ -16,6 +17,7 @@ import com.vayunmathur.weather.data.GeoDatabase object WeatherApi {      private const val BUNDLE_BASE = "https://api.maproj.org/wx/v1"+    private const val TAG = "WeatherApi"      // Test seam: point the bundle API at an unroutable address so the     // failure-path tests are hermetic on boxes that have internet.@@ -30,6 +32,19 @@ object WeatherApi {      * — callers wrap in try/catch and fall back to cache.      */     suspend fun bundle(latitude: Double, longitude: Double, fields: String = "all"): WxBundle {+        // Full bundles come from the static R2 tiles first (computed on+        // device, identical to the server's); any failure there — ocean+        // point, no network to R2, a format change — falls back to the API.+        // Tests that point the API somewhere (bundleBaseOverride) skip it.+        if (fields == "all" && bundleBaseOverride == null && WxStatic.enabled) {+            try {+                return WxStatic.bundle(latitude, longitude)+            } catch (e: kotlinx.coroutines.CancellationException) {+                throw e+            } catch (@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Exception) {+                Log.status(TAG, "static weather unavailable (${e.javaClass.simpleName}: ${e.message}); using the API")+            }+        }         val url = buildString {             append(bundleBase).append("/bundle")             append("?lat=").append(latitude)
weather/src/main/java/com/vayunmathur/weather/network/WxStatic.kt
diff --git a/weather/src/main/java/com/vayunmathur/weather/network/WxStatic.kt b/weather/src/main/java/com/vayunmathur/weather/network/WxStatic.ktnew file mode 100644index 0000000000..5beb0a8f28--- /dev/null+++ b/weather/src/main/java/com/vayunmathur/weather/network/WxStatic.kt@@ -0,0 +1,238 @@+package com.vayunmathur.weather.network++import android.content.Context+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.weather.domain.wx.WxCompute+import com.vayunmathur.weather.domain.wx.WxGrid+import com.vayunmathur.weather.domain.wx.WxTiles+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext+import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import java.io.File++/**+ * Weather from static files on Cloudflare R2 (bucket `static`,+ * `https://static.maproj.org/wx/v1/`,+ * written by the server's `wx export`): `latest.json` names the current run,+ * one `WXT1` tile per ~1°×1° block holds every model series a bundle needs,+ * and a static `WXG1` geo block gives the point's elevation and time zone.+ * The bundle is computed on device ([WxCompute]), identical to the server's.+ *+ * Traffic: `latest.json` is re-read only after its `next_check` (the next+ * model run, ~6 h), so an hourly refresh is usually zero requests; a new run+ * costs one tile GET per location tile (+ one finished-day history object a+ * day); geo blocks are fetched once ever.+ * Everything is cached on disk by run id. Any failure throws and+ * [WeatherApi.bundle] falls back to the server API, so the rollout is safe.+ */+object WxStatic {+    private const val BASE = "https://static.maproj.org/wx/v1/"+    private const val HTTP_OK = 200+    private const val HTTP_FORBIDDEN = 403 // R2 answers a missing public key with 404 or 403+    private const val HTTP_NOT_FOUND = 404+    private const val MS_PER_S = 1000L++    /** Don't re-poll `latest.json` more often than this after `next_check`. */+    private const val POLL_MIN_SECS = 15 * 60L++    /** Re-poll even before `next_check` once the manifest is this old. */+    private const val MANIFEST_MAX_AGE_SECS = 12 * 3600L++    @androidx.annotation.VisibleForTesting+    internal var baseOverride: String? = null++    /** Kill switch (tests, or a remote flag later). */+    @Volatile+    var enabled: Boolean = true++    /** Test seam: object fetch (url → status + bytes). */+    @androidx.annotation.VisibleForTesting+    internal var fetcher: suspend (String) -> Pair<Int, ByteArray> = { url -> NetworkClient.performRequestBytes(url) }++    private val base get() = baseOverride ?: BASE+    private val json = Json { ignoreUnknownKeys = true }+    private val lock = Mutex()++    @Volatile+    private var dir: File? = null+    private var manifest: Pair<Manifest, Long>? = null+    private val tiles = HashMap<String, WxTiles.Tile?>()+    private val geos = HashMap<String, WxTiles.GeoBlock>()+    private val hists = HashMap<String, WxTiles.Tile>()++    @Serializable+    internal data class Grid(val ny: Int, val nx: Int, val cells: Int)++    /** Per-day history objects `hist/<day>/<ty>/<tx>.wxt` for days `[fromDay, toDay)`. */+    @Serializable+    internal data class Hist(+        val base: String,+        @SerialName("from_day") val fromDay: Long,+        @SerialName("to_day") val toDay: Long,+    )++    @Serializable+    internal data class Manifest(+        val v: Int,+        val run: String,+        val base: String,+        @SerialName("next_check") val nextCheck: Long,+        val grid: Grid,+        val hist: Hist,+        val geo: String = "geo/v1/",+    )++    /** This point/run cannot be served from R2 (ocean, missing object, clock skew): use the API. */+    class NotCovered(msg: String, cause: Throwable? = null) : Exception(msg, cause)++    /** Disk cache under the app's cache dir (call from activity + worker). */+    fun init(context: Context) {+        if (dir == null) dir = File(context.applicationContext.cacheDir, "wx-static").apply { mkdirs() }+    }++    private suspend fun get(path: String): ByteArray? {+        val (status, bytes) = fetcher(base + path)+        return when (status) {+            HTTP_OK -> bytes+            HTTP_FORBIDDEN, HTTP_NOT_FOUND -> null+            else -> throw java.io.IOException("wx static $path: HTTP $status")+        }+    }++    private fun file(name: String): File? = dir?.let { File(it, name) }++    private fun writeAtomic(f: File?, bytes: ByteArray) {+        if (f == null) return+        f.parentFile?.mkdirs()+        val tmp = File(f.path + ".tmp")+        tmp.writeBytes(bytes)+        tmp.renameTo(f)+    }++    // Offline with a cached manifest: the IOException is the expected signal+    // to keep serving the cached run, not an error to propagate.+    @Suppress("SwallowedException", "ThrowsCount")+    private suspend fun currentManifest(now: Long): Manifest {+        val cached = manifest ?: file("latest.json")?.takeIf { it.exists() }?.let { f ->+            runCatching { json.decodeFromString<Manifest>(f.readText()) to f.lastModified() / MS_PER_S }.getOrNull()+        }+        if (cached != null) {+            val (m, fetchedAt) = cached+            val due = now >= m.nextCheck || now - fetchedAt >= MANIFEST_MAX_AGE_SECS+            if (!due || now - fetchedAt < POLL_MIN_SECS) {+                manifest = cached+                return m+            }+        }+        val fresh = try {+            get("latest.json") ?: throw NotCovered("no latest.json")+        } catch (e: java.io.IOException) {+            // Offline: keep using the cached run (its tiles stay valid).+            cached?.let { return it.first } ?: throw e+        }+        val m = json.decodeFromString<Manifest>(fresh.decodeToString())+        if (m.v != 1) throw NotCovered("manifest v${m.v}")+        writeAtomic(file("latest.json"), fresh)+        if (cached != null && cached.first.run != m.run) {+            // A new run: older tiles are dead weight.+            file("t")?.deleteRecursively()+            tiles.clear()+        }+        manifest = m to now+        return m+    }++    @Suppress("ThrowsCount")+    private suspend fun tile(m: Manifest, ty: Int, tx: Int): WxTiles.Tile {+        val key = "${m.run}/$ty/$tx"+        if (tiles.containsKey(key)) return tiles[key] ?: throw NotCovered("no tile $key")+        val f = file("t/${m.run}_${ty}_$tx.wxt")+        val miss = file("t/${m.run}_${ty}_$tx.none")+        if (miss?.exists() == true) {+            tiles[key] = null+            throw NotCovered("no tile $key")+        }+        val bytes = f?.takeIf { it.exists() }?.readBytes() ?: get("${m.base}$ty/$tx.wxt")?.also { writeAtomic(f, it) }+        if (bytes == null) {+            // Ocean / not exported: remember for this run.+            writeAtomic(miss, ByteArray(0))+            tiles[key] = null+            throw NotCovered("no tile $key")+        }+        return WxTiles.decodeTile(bytes).also { tiles[key] = it }+    }++    /**+     * The finished days before the run tile (immutable: cached for good,+     * days older than any window dropped). Usually all cached: a new day+     * object appears once a day.+     */+    private suspend fun history(m: Manifest, ty: Int, tx: Int, now: Long): List<WxTiles.Tile> {+        val days = WxGrid.histDaysNeeded(now, m.hist.toDay * 24)+        if (!days.isEmpty() && days.first < m.hist.fromDay) throw NotCovered("history before ${m.hist.fromDay}")+        val out = days.map { d ->+            val key = "$d/$ty/$tx"+            hists[key] ?: run {+                val f = file("h/${d}_${ty}_$tx.wxt")+                val bytes = f?.takeIf { it.exists() }?.readBytes()+                    ?: get("${m.hist.base}$key.wxt")?.also { writeAtomic(f, it) }+                    ?: throw NotCovered("no history $key")+                WxTiles.decodeTile(bytes).also { hists[key] = it }+            }+        }+        if (!days.isEmpty()) {+            val oldest = days.first - 1+            hists.keys.removeAll { it.substringBefore('/').toLong() < oldest }+            file("h")?.listFiles()?.forEach { f ->+                val day = f.name.substringBefore('_').toLongOrNull()+                if (day != null && day < oldest) f.delete()+            }+        }+        return out+    }++    private suspend fun geo(m: Manifest, k: WxGrid.GeoKey): WxTiles.GeoBlock {+        val key = "${k.x}/${k.y}/${k.b}"+        geos[key]?.let { return it }+        val f = file("g/${k.x}_${k.y}_${k.b}.wxg")+        val bytes = f?.takeIf { it.exists() }?.readBytes()+            ?: get("${m.geo}$key.wxg")?.also { writeAtomic(f, it) }+            ?: throw NotCovered("no geo block $key")+        return WxTiles.decodeGeo(bytes).also { geos[key] = it }+    }++    /**+     * The full bundle for (lat, lon) at [nowEpoch] from R2. Throws on any+     * failure ([NotCovered] for points without a tile, e.g. open ocean).+     */+    @Suppress("ThrowsCount")+    suspend fun bundle(lat: Double, lon: Double, nowEpoch: Long = System.currentTimeMillis() / MS_PER_S): WxBundle =+        withContext(Dispatchers.IO) {+            if (!enabled) throw NotCovered("disabled")+            val (t, hist, g) = lock.withLock {+                val m = currentManifest(nowEpoch)+                val (ty, tx) = WxGrid.tileOf(lat, lon, m.grid.ny, m.grid.nx, m.grid.cells)+                val k = WxGrid.geoOf(lat, lon) ?: throw NotCovered("off the DEM grid")+                Triple(tile(m, ty, tx), history(m, ty, tx, nowEpoch), geo(m, k))+            }+            val s = try {+                WxGrid.seriesFromTile(t, hist, g, lat, lon, nowEpoch)+            } catch (e: WxGrid.Unavailable) {+                throw NotCovered(e.message ?: "unavailable", e)+            }+            WxCompute.computeBundle(lat, lon, nowEpoch, t.iconRunIso, s)+        }++    @androidx.annotation.VisibleForTesting+    internal fun resetForTest() {+        manifest = null+        tiles.clear()+        geos.clear()+        hists.clear()+        dir = null+    }+}
weather/src/test/java/com/vayunmathur/weather/domain/wx/WxParityTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/domain/wx/WxParityTest.kt b/weather/src/test/java/com/vayunmathur/weather/domain/wx/WxParityTest.ktindex dd961e5243..9fb55470dd 100644--- a/weather/src/test/java/com/vayunmathur/weather/domain/wx/WxParityTest.kt+++ b/weather/src/test/java/com/vayunmathur/weather/domain/wx/WxParityTest.kt@@ -31,25 +31,34 @@ import java.util.zip.GZIPInputStream  * produces the same bundle, value for value.  */ class WxParityTest {-    private val json = Json { ignoreUnknownKeys = true }+    // encodeDefaults: the server always writes v/model/step; a missing key+    // and an explicit null compare equal below (serde omits None sections).+    private val json = Json {+        ignoreUnknownKeys = true+        encodeDefaults = true+    }      private fun res(path: String): ByteArray =         javaClass.classLoader!!.getResourceAsStream("wx/$path")?.use { it.readBytes() }             ?: error("missing fixture wx/$path") +    private fun isNumber(e: JsonElement) = e is JsonPrimitive && e !is JsonNull && !e.isString+     /** First difference between two JSON trees (numbers compared as doubles). */     private fun diff(path: String, a: JsonElement, b: JsonElement): String? = when {         a is JsonObject && b is JsonObject -> (a.keys + b.keys).firstNotNullOfOrNull { k ->             diff("$path.$k", a[k] ?: JsonNull, b[k] ?: JsonNull)         }-        a is JsonArray && b is JsonArray ->-            if (a.size != b.size) "$path: len ${a.size} != ${b.size}"-            else a.indices.firstNotNullOfOrNull { k -> diff("$path[$k]", a[k], b[k]) }-        a is JsonPrimitive && b is JsonPrimitive && !a.isString && !b.isString && a !is JsonNull && b !is JsonNull ->-            if (a.doubleOrNull == b.doubleOrNull) null else "$path: $a != $b"+        a is JsonArray && b is JsonArray -> diffArrays(path, a, b)+        isNumber(a) && isNumber(b) ->+            if (a.jsonPrimitive.doubleOrNull == b.jsonPrimitive.doubleOrNull) null else "$path: $a != $b"         else -> if (a == b) null else "$path: $a != $b"     } +    private fun diffArrays(path: String, a: JsonArray, b: JsonArray): String? =+        if (a.size != b.size) "$path: len ${a.size} != ${b.size}"+        else a.indices.firstNotNullOfOrNull { k -> diff("$path[$k]", a[k], b[k]) }+     @Test     fun `every fixture bundle computed on device equals the server bundle`() {         val cases = json.parseToJsonElement(res("cases.json").decodeToString()).jsonArray
weather/src/test/java/com/vayunmathur/weather/network/WxStaticTest.kt
diff --git a/weather/src/test/java/com/vayunmathur/weather/network/WxStaticTest.kt b/weather/src/test/java/com/vayunmathur/weather/network/WxStaticTest.ktnew file mode 100644index 0000000000..c345224a37--- /dev/null+++ b/weather/src/test/java/com/vayunmathur/weather/network/WxStaticTest.kt@@ -0,0 +1,86 @@+package com.vayunmathur.weather.network++import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.long+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Assert.fail+import org.junit.Before+import org.junit.Test++/**+ * [WxStatic] request behaviour against the fixture objects (no network):+ * the first bundle costs latest.json + tile + the finished-day history+ * objects + geo block, later refreshes of the same run cost nothing until+ * `next_check`, a missing tile is a clean+ * [WxStatic.NotCovered] (→ API fallback) and is not re-requested.+ */+class WxStaticTest {+    private val json = Json { ignoreUnknownKeys = true }+    private val requests = mutableListOf<String>()++    private fun res(path: String): ByteArray? =+        javaClass.classLoader!!.getResourceAsStream("wx/$path")?.use { it.readBytes() }++    @Before+    fun setUp() {+        WxStatic.resetForTest()+        WxStatic.baseOverride = "https://r2.test/wx/v1/"+        WxStatic.fetcher = { url ->+            requests += url.removePrefix("https://r2.test/wx/v1/")+            val body = res(url.removePrefix("https://r2.test/wx/v1/"))+            if (body == null) 404 to ByteArray(0) else 200 to body+        }+    }++    @After+    fun tearDown() {+        WxStatic.resetForTest()+        WxStatic.baseOverride = null+        WxStatic.fetcher = { url -> com.vayunmathur.library.network.NetworkClient.performRequestBytes(url) }+    }++    @Test+    fun `refresh costs one manifest, one tile and one geo block, then nothing`() = runBlocking {+        val case = json.parseToJsonElement(res("cases.json")!!.decodeToString()).jsonArray[0].jsonObject+        val lat = case["lat"]!!.jsonPrimitive.content.toDouble()+        val lon = case["lon"]!!.jsonPrimitive.content.toDouble()+        val now = case["now"]!!.jsonPrimitive.long+        val b = WxStatic.bundle(lat, lon, now)+        assertTrue(b.hourly != null && b.current != null)+        val hist = case["hist"]!!.jsonArray.map { it.jsonPrimitive.content }+        assertTrue("first fetch needs the finished days", hist.size >= 7)+        assertEquals(+            listOf("latest.json", case["tile"]!!.jsonPrimitive.content) + hist + case["geo"]!!.jsonPrimitive.content,+            requests,+        )+        val first = requests.size+        // Same run, an hour later: computed locally, zero requests.+        WxStatic.bundle(lat, lon, now + 3600)+        assertEquals(first, requests.size)+        // Past next_check the manifest is re-read (once), tiles stay cached.+        val latest = json.parseToJsonElement(res("latest.json")!!.decodeToString()).jsonObject+        val next = latest["next_check"]!!.jsonPrimitive.long+        WxStatic.bundle(lat, lon, maxOf(next, now) + 20 * 60)+        assertEquals(listOf("latest.json"), requests.drop(first))+    }++    @Test+    fun `an ocean point without a tile is NotCovered and not refetched`() = runBlocking {+        val first = json.parseToJsonElement(res("cases.json")!!.decodeToString()).jsonArray[0].jsonObject+        val now = first["now"]!!.jsonPrimitive.long+        repeat(2) {+            try {+                WxStatic.bundle(-40.0, -130.0, now) // South Pacific+                fail("expected NotCovered")+            } catch (_: WxStatic.NotCovered) {+            }+        }+        assertEquals(1, requests.count { it.endsWith(".wxt") })+    }+}