Modern Apps git

← Modern-Apps.git

news: read the feed from R2 static first

Commit
60bf26a6f33a93f7bde43f52b8bff2333c6a9ad9
Author
Vayun Mathur <[email protected]>
When
2026-11-25 23:50 UTC (10 days ago)
Parents
f1f37ac
Networking.fetchServerFeedText now reads https://static.maproj.org/news/v1/news.json via StaticMirror (accepted fresh for 1 h by Last-Modified) and falls back to the origin GET /news.json, then to the existing on-device sitemap/RSS crawl, with the Room-cached feed visible throughout. TrustBundle.SYSTEM already covers the static host. NewsRepository gains a serverFeedFetch seam for tests; refresh/timeout/empty-parse behaviour and story grouping are unchanged (no local clustering).

Verified: :news:testDevUnitTest and :news:lint pass, including a URL/fallback contract test.

Diff

news/AGENTS.md
diff --git a/news/AGENTS.md b/news/AGENTS.mdindex 7a75b18eb5..b79c9303c6 100644--- a/news/AGENTS.md+++ b/news/AGENTS.md@@ -11,12 +11,20 @@ _Install: ./install news_ - Rust: no / screenshotTest: yes (phone + large-tablet)  ## Overview-**Purpose:** News reader. Primary feed is our server's `GET /news.json`-(`https://api.maproj.org/news.json`, see `domain/ServerFeedParser` for the-contract + assumptions), merged into Room. Every source is always in the-corpus (no per-source toggle); category + search are the filters, and the persisted-Top stories / Latest sort (`domain/FeedRanking`) orders the feed-client-side. If the server fetch fails/times out/parses empty, refresh+**Purpose:** News reader. Primary feed is our server's merged+`news.json` snapshot, read first from its static copy on R2+(`https://static.maproj.org/news/v1/news.json`, republished by the+server on every refresh) with the origin `GET /news.json`+(`https://api.maproj.org/news.json`, see `domain/ServerFeedParser` for+the contract + assumptions) as fallback when the static copy is+missing, failing, or older than 1 hour; the result is merged into Room. Every source is always in the+corpus (no per-source toggle); category + search are the filters, and+`domain/FeedRanking` orders the story feed client-side by descending+source count, then newest first (search keeps its relevance order).+Every feed item is a story (`domain/Story`, mechanical grouping by+exact server `storyId` only — singletons included), shown as a card+labelled only with its source count ("1 source" / "N sources", no+lead-source name) and opening the story view. If the server fetch fails/times out/parses empty, refresh falls back to the on-device per-source sitemap/RSS crawl of all sources (cached feed stays visible either way). Article reading is always on-device: publisher HTML is fetched directly and extracted locally. No account.@@ -57,8 +65,11 @@ Japan Times (sitemap URL serves HTML, not XML). (DataStore owner) → `network/Networking` (the single networking entry point, `NetworkClient` with `TrustBundle.SYSTEM` — publisher hosts are arbitrary, so no reduced bundle can cover them; SYSTEM also covers-api.maproj.org, whereas FIRST_PARTY would break publisher fetches) →-`domain/` parsers and extractor (pure, no Android imports).+api.maproj.org and static.maproj.org, whereas FIRST_PARTY would break+publisher fetches; the server feed goes through+`Networking.fetchServerFeedText` → `StaticMirror.get`, static first,+origin fallback) → `domain/` parsers and extractor (pure, no Android+imports).  ## Entry points + reading order `Route` (`Feed` / `Reader(url)` / `Saved`) → `MainActivity.kt`@@ -72,6 +83,9 @@ api.maproj.org, whereas FIRST_PARTY would break publisher fetches) → - Extraction quality is judged by `ExtractedArticle.bodyChars`; truncated   extractions usually mean the source changed its markup or paywall. +## Screenshot coverage+Every `Route` leaf (`Feed`/`Story`/`Reader`/`Saved`/`LocalLocation`/`Settings`) has a capture in `src/screenshotTest` named `<n>-<route-key>`; the fatal `RouteScreenshotCoverage` lint enforces it (no exemptions here). News has no dialogs — dialog UI, if added, must be a `Route` destination with `DialogPage()` metadata, not state in a screen. Convention: `docs/screenshot-coverage.md`.+ ## Verify (this module only) ``` ./gradlew :news:compileDevKotlin
news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt
diff --git a/news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt b/news/src/main/java/com/vayunmathur/news/data/NewsRepository.ktindex 316394cc65..89fbc36228 100644--- a/news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt+++ b/news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt@@ -29,7 +29,10 @@ import kotlinx.serialization.json.Json /**  * Owns the Room cache and all feed/article fetching. The [fetch] seam  * defaults to [Networking] and is replaced by a fake in unit tests, so- * no test touches the network. Bodies are extracted on device only.+ * no test touches the network; the server feed goes through the+ * [serverFeedFetch] seam (defaults to [Networking.fetchServerFeedText]:+ * R2 static copy first, origin as fallback). Bodies are extracted on+ * device only.  *  * Refresh topology (fixed 2026-11-23, was the ANR / "stuck feed" bug):  * sources fetch in parallel, each on [feedDispatcher] (never Main —@@ -45,6 +48,7 @@ class NewsRepository internal constructor(     private val fetch: suspend (String) -> String,     private val feedDispatcher: CoroutineDispatcher = Dispatchers.Default,     private val sourceTimeoutMs: Long = SOURCE_TIMEOUT_MS,+    private val serverFeedFetch: suspend () -> String = { Networking.fetchServerFeedText() }, ) : RoomRepository<NewsDatabase>(context, NewsDatabase::class, DB_NAME) {      constructor(context: Context) : this(context, Networking::fetchText)@@ -61,7 +65,9 @@ class NewsRepository internal constructor(         dao.setBookmarked(url, bookmarked)      /**-     * Primary path: one fetch of the server's `news.json`, merged into+     * Primary path: one fetch of the server feed (its R2 static copy+     * first, the origin `news.json` as fallback — see+     * [Networking.fetchServerFeedText]), merged into      * Room exactly like a crawl result. Every source the server carries      * is always included — there is no client-side enabled-source      * filter; categories and search are the filters. [sources] only@@ -92,7 +98,7 @@ class NewsRepository internal constructor(     private suspend fun fetchServerFeed(): List<FeedArticle>? {         val articles = try {             withTimeoutOrNull(sourceTimeoutMs) {-                withContext(feedDispatcher) { ServerFeedParser.parse(fetch(Networking.SERVER_FEED_URL)) }+                withContext(feedDispatcher) { ServerFeedParser.parse(serverFeedFetch()) }             }         } catch (e: CancellationException) {             throw e
news/src/main/java/com/vayunmathur/news/network/Networking.kt
diff --git a/news/src/main/java/com/vayunmathur/news/network/Networking.kt b/news/src/main/java/com/vayunmathur/news/network/Networking.ktindex 90298aa54e..d563150bb7 100644--- a/news/src/main/java/com/vayunmathur/news/network/Networking.kt+++ b/news/src/main/java/com/vayunmathur/news/network/Networking.kt@@ -1,33 +1,63 @@ package com.vayunmathur.news.network  import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.StaticMirror import java.io.IOException  /**  * The news app's single networking entry point. Owns the client, the  * browser-like request headers publisher CDNs expect, and status mapping.  *- * Feed primary path is our server's `GET /news.json` at [SERVER_FEED_URL]- * — `https://api.maproj.org`, the same API host findfamily/everysync use- * (root AGENTS.md: "The server's canonical API host is api.maproj.org").+ * Feed primary path is the server's static copy of `GET /news.json` on+ * R2 at [STATIC_FEED_URL] (`https://static.maproj.org/news/v1/news.json`,+ * republished by the server on every 12-minute refresh), read through+ * [StaticMirror] with [SERVER_FEED_URL] — `https://api.maproj.org`, the+ * same API host findfamily/everysync use (root AGENTS.md: "The server's+ * canonical API host is api.maproj.org") — as the fallback when the+ * static copy is missing, failing, or older than [STATIC_MAX_AGE_MS].  * Article bodies and the offline sitemap/RSS fallback still fetch  * publisher URLs directly on-device.  *  * Trust stays SYSTEM (initialised in MainActivity), not FIRST_PARTY:  * FIRST_PARTY pins only cover api.maproj.org and would break every  * publisher fetch, while SYSTEM (platform roots, incl. the public CA- * chain api.maproj.org serves) covers both. Narrowing would need a+ * chain api.maproj.org serves) covers api.maproj.org,+ * static.maproj.org, and the publisher hosts. Narrowing would need a  * per-host client, which NetworkClient does not offer.  */ object Networking {     /** Server feed (location_share_server `GET /news.json`); see ServerFeedParser for the contract. */     const val SERVER_FEED_URL = "https://api.maproj.org/news.json"++    /** The server's copy of the same feed on R2 (read first); key `news/v1/news.json` in the static bucket. */+    const val STATIC_FEED_URL = "${StaticMirror.BASE}/news/v1/news.json"++    /**+     * Older static copies mean the server stopped republishing them+     * (refresh is every 12 min): ask the origin directly instead. Five+     * missed refresh cycles of slack, then the origin wins.+     */+    const val STATIC_MAX_AGE_MS = 60L * 60 * 1000     private val headers = mapOf(         "User-Agent" to "Mozilla/5.0 (Linux; Android 14) NewsReader",         "Accept" to "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",         "Accept-Language" to "en-GB,en;q=0.8",     ) +    /**+     * The merged server feed as text: the R2 static copy first+     * ([StaticMirror.get]-style, fresh within [STATIC_MAX_AGE_MS]), the+     * origin `GET /news.json` as fallback. Throws [IOException] when the+     * fallback answers non-2xx, exactly like [fetchText], so the+     * repository's failure handling (cached feed, then on-device crawl)+     * is unchanged.+     */+    suspend fun fetchServerFeedText(): String {+        val response = StaticMirror.get(STATIC_FEED_URL, SERVER_FEED_URL, STATIC_MAX_AGE_MS)+        if (!response.isSuccess) throw IOException("HTTP ${response.status} for $SERVER_FEED_URL")+        return response.text+    }+     /**      * GET [url] as text; throws [IOException] on transport failure or non-2xx.      * Explicit per-request timeouts (the client's pooled defaults are
news/src/test/java/com/vayunmathur/news/data/NewsRepositoryTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/data/NewsRepositoryTest.kt b/news/src/test/java/com/vayunmathur/news/data/NewsRepositoryTest.ktindex 85e1de8495..5cb34d3970 100644--- a/news/src/test/java/com/vayunmathur/news/data/NewsRepositoryTest.kt+++ b/news/src/test/java/com/vayunmathur/news/data/NewsRepositoryTest.kt@@ -50,7 +50,7 @@ class NewsRepositoryTest {     fun refreshFollowsIndexAndCachesArticles() = runBlocking {         val context = ApplicationProvider.getApplicationContext<Context>()         val calls = mutableListOf<String>()-        val repo = NewsRepository(context, fakeFetch(calls))+        val repo = NewsRepository(context, fakeFetch(calls), serverFeedFetch = { throw java.io.IOException("offline") })         val source = SourceCatalog.byId("bbc")!!.copy(feedUrl = "https://fake.example/index.xml")         val failed = repo.refresh(listOf(source))         assertTrue(failed.isEmpty())@@ -64,7 +64,7 @@ class NewsRepositoryTest {     fun articleBodyExtractsAndCaches() = runBlocking {         val context = ApplicationProvider.getApplicationContext<Context>()         val calls = mutableListOf<String>()-        val repo = NewsRepository(context, fakeFetch(calls))+        val repo = NewsRepository(context, fakeFetch(calls), serverFeedFetch = { throw java.io.IOException("offline") })         val body = repo.articleBody("https://fake.example/story")         assertEquals("Fake Story", body.title)         assertEquals(2, body.blocks.size)@@ -87,6 +87,7 @@ class NewsRepositoryTest {                 fastUrlset             },             sourceTimeoutMs = 500,+            serverFeedFetch = { throw java.io.IOException("offline") },         )         val fast = SourceCatalog.byId("bbc")!!.copy(name = "Fast", feedUrl = "https://fake.example/fast.xml")         val hanging = SourceCatalog.byId("guardian")!!.copy(name = "Hang", feedUrl = "https://fake.example/hang.xml")@@ -106,7 +107,7 @@ class NewsRepositoryTest {     fun cachedArticlesEmitWithoutRefresh() = runBlocking {         val context = ApplicationProvider.getApplicationContext<Context>()         val calls = mutableListOf<String>()-        val repo = NewsRepository(context, fakeFetch(calls))+        val repo = NewsRepository(context, fakeFetch(calls), serverFeedFetch = { throw java.io.IOException("offline") })         val source = SourceCatalog.byId("bbc")!!.copy(feedUrl = "https://fake.example/index.xml")         repo.refresh(listOf(source))         // No refresh in flight: the Room cache alone must serve the feed.@@ -122,7 +123,7 @@ class NewsRepositoryTest {         val repo = NewsRepository(context, fetch = { _ ->             seenThreads += Thread.currentThread().name             childUrlset-        })+        }, serverFeedFetch = { throw java.io.IOException("offline") })         val source = SourceCatalog.byId("bbc")!!.copy(feedUrl = "https://fake.example/direct.xml")         repo.refresh(listOf(source))         assertTrue(seenThreads.isNotEmpty())@@ -135,7 +136,7 @@ class NewsRepositoryTest {     @Test     fun failingSourceIsReportedNotThrown() = runBlocking {         val context = ApplicationProvider.getApplicationContext<Context>()-        val repo = NewsRepository(context, fetch = { throw java.io.IOException("offline") })+        val repo = NewsRepository(context, fetch = { throw java.io.IOException("offline") }, serverFeedFetch = { throw java.io.IOException("offline") })         val failed = repo.refresh(listOf(SourceCatalog.sources.first()))         assertEquals(1, failed.size)     }
news/src/test/java/com/vayunmathur/news/data/NewsServerFeedTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/data/NewsServerFeedTest.kt b/news/src/test/java/com/vayunmathur/news/data/NewsServerFeedTest.ktindex 7f097efff6..9dfebbbaf1 100644--- a/news/src/test/java/com/vayunmathur/news/data/NewsServerFeedTest.kt+++ b/news/src/test/java/com/vayunmathur/news/data/NewsServerFeedTest.kt@@ -43,14 +43,28 @@ class NewsServerFeedTest {     @Test fun refreshPrefersServerFeedAndDoesNotCrawl() = runBlocking {         val context = ApplicationProvider.getApplicationContext<Context>()         val calls = mutableListOf<String>()-        val repo = NewsRepository(context, fetch = { url -> calls += url; serverJson })+        var serverCalls = 0+        val repo = NewsRepository(+            context,+            fetch = { url -> calls += url; serverJson },+            serverFeedFetch = { serverCalls++; serverJson },+        )         val failed = repo.refresh(SourceCatalog.sources)         assertTrue(failed.isEmpty())-        assertEquals(listOf(Networking.SERVER_FEED_URL), calls, "primary path must be the single server fetch")+        assertEquals(1, serverCalls, "primary path must be the single server-feed fetch")+        assertTrue(calls.isEmpty(), "server feed success must not crawl sources, saw $calls")         val cached = withTimeout(10_000) { repo.articles.first { a -> a.any { it.url == "https://srv.example/alpha" } } }         assertTrue(cached.any { it.title == "Server Alpha Volcano" })     } +    @Test fun staticFeedUrlIsTheR2CopyWithOriginFallback() {+        // The contract the server publishes to (location_share_server+        // NEWS_R2_KEY) and the app's fallback order.+        assertEquals("https://static.maproj.org/news/v1/news.json", Networking.STATIC_FEED_URL)+        assertEquals("https://api.maproj.org/news.json", Networking.SERVER_FEED_URL)+        assertTrue(Networking.STATIC_MAX_AGE_MS > 0)+    }+     @Test fun refreshIncludesServerArticlesFromEverySource() = runBlocking {         val context = ApplicationProvider.getApplicationContext<Context>()         val filterJson = """@@ -61,7 +75,7 @@ class NewsServerFeedTest {                "published_at":"2026-11-23T09:00:00Z"}             ]}         """.trimIndent()-        val repo = NewsRepository(context, fetch = { filterJson })+        val repo = NewsRepository(context, fetch = { filterJson }, serverFeedFetch = { filterJson })         // No enabled-source filter exists: even though only BBC drives         // the (unused) fallback list, the Guardian server article lands.         val failed = repo.refresh(listOf(SourceCatalog.byId("bbc")!!))@@ -73,11 +87,11 @@ class NewsServerFeedTest {     @Test fun serverFailureFallsBackToSourceCrawl() = runBlocking {         val context = ApplicationProvider.getApplicationContext<Context>()         val calls = mutableListOf<String>()-        val repo = NewsRepository(context, fetch = { url ->-            calls += url-            if (url == Networking.SERVER_FEED_URL) throw IOException("server unreachable")-            fallbackUrlset-        })+        val repo = NewsRepository(+            context,+            fetch = { url -> calls += url; fallbackUrlset },+            serverFeedFetch = { calls += Networking.SERVER_FEED_URL; throw IOException("server unreachable") },+        )         val bbc = SourceCatalog.byId("bbc")!!.copy(feedUrl = "https://srv.example/fallback.xml")         val failed = repo.refresh(listOf(bbc))         assertTrue(failed.isEmpty(), "fallback crawl success must not report failure")@@ -89,13 +103,11 @@ class NewsServerFeedTest {      @Test fun searchRanksTitleHitBeforeDownloadedBodyHit() = runBlocking {         val context = ApplicationProvider.getApplicationContext<Context>()-        val repo = NewsRepository(context, fetch = { url ->-            when {-                url == Networking.SERVER_FEED_URL -> serverJson-                url.endsWith("/beta") -> articleHtml-                else -> serverJson-            }-        })+        val repo = NewsRepository(+            context,+            fetch = { url -> if (url.endsWith("/beta")) articleHtml else serverJson },+            serverFeedFetch = { serverJson },+        )         repo.refresh(SourceCatalog.sources)         withTimeout(10_000) { repo.articles.first { a -> a.any { it.url == "https://srv.example/beta" } } }         // Title hit: "volcano" is only in Alpha's title.
news/src/test/java/com/vayunmathur/news/platform/NewsViewModelCategoryTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/platform/NewsViewModelCategoryTest.kt b/news/src/test/java/com/vayunmathur/news/platform/NewsViewModelCategoryTest.ktindex 1a38494f40..22d853e15b 100644--- a/news/src/test/java/com/vayunmathur/news/platform/NewsViewModelCategoryTest.kt+++ b/news/src/test/java/com/vayunmathur/news/platform/NewsViewModelCategoryTest.kt@@ -60,9 +60,11 @@ class NewsViewModelCategoryTest {     @Test fun categoryFilterAllPassthroughAndSearchWithinCategory() {         val context = ApplicationProvider.getApplicationContext<Application>()         seedNewsDb(context)-        val repository = NewsRepository(context, fetch = { url ->-            if (url.contains("news.json")) serverJson else throw IOException("offline")-        })+        val repository = NewsRepository(+            context,+            fetch = { throw IOException("offline") },+            serverFeedFetch = { serverJson },+        )         // Pre-land the server feed in Room so the ViewModel flows have data         // regardless of its init-refresh timing.         runBlocking { repository.refresh(SourceCatalog.sources) }
news/src/test/java/com/vayunmathur/news/platform/NewsViewModelLocalTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/platform/NewsViewModelLocalTest.kt b/news/src/test/java/com/vayunmathur/news/platform/NewsViewModelLocalTest.ktindex 961b80eec4..dfa6510f78 100644--- a/news/src/test/java/com/vayunmathur/news/platform/NewsViewModelLocalTest.kt+++ b/news/src/test/java/com/vayunmathur/news/platform/NewsViewModelLocalTest.kt@@ -63,9 +63,11 @@ class NewsViewModelLocalTest {     @Test fun localLocationBoostsMatchingSourcesFirstAndUnsetRestores() {         val context = ApplicationProvider.getApplicationContext<Application>()         seedNewsDb(context)-        val repository = NewsRepository(context, fetch = { url ->-            if (url.contains("news.json")) serverJson else throw IOException("offline")-        })+        val repository = NewsRepository(+            context,+            fetch = { throw IOException("offline") },+            serverFeedFetch = { serverJson },+        )         runBlocking { repository.refresh(SourceCatalog.sources) }         val prefs = NewsPrefs(context)         val viewModel = NewsViewModel(context, repository, prefs)
news/src/test/java/com/vayunmathur/news/ui/FeedScreenTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/ui/FeedScreenTest.kt b/news/src/test/java/com/vayunmathur/news/ui/FeedScreenTest.ktindex fee4d9bd8f..954b7f3da9 100644--- a/news/src/test/java/com/vayunmathur/news/ui/FeedScreenTest.kt+++ b/news/src/test/java/com/vayunmathur/news/ui/FeedScreenTest.kt@@ -38,7 +38,7 @@ class FeedScreenTest {     private fun viewModel(): NewsViewModel {         val context = ApplicationProvider.getApplicationContext<Application>()         seedNewsDb(context)-        val repository = NewsRepository(context, fetch = { throw IOException("offline") })+        val repository = NewsRepository(context, fetch = { throw IOException("offline") }, serverFeedFetch = { throw IOException("offline") })         return NewsViewModel(context, repository, NewsPrefs(context))     } 
news/src/test/java/com/vayunmathur/news/ui/SettingsScreenTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/ui/SettingsScreenTest.kt b/news/src/test/java/com/vayunmathur/news/ui/SettingsScreenTest.ktindex 2f228990a4..2e68021a73 100644--- a/news/src/test/java/com/vayunmathur/news/ui/SettingsScreenTest.kt+++ b/news/src/test/java/com/vayunmathur/news/ui/SettingsScreenTest.kt@@ -25,7 +25,7 @@ class SettingsScreenTest {     @Test fun localLocationSettingRowNavigatesToPicker() {         val context = ApplicationProvider.getApplicationContext<Application>()         seedNewsDb(context)-        val repository = NewsRepository(context, fetch = { throw IOException("offline") })+        val repository = NewsRepository(context, fetch = { throw IOException("offline") }, serverFeedFetch = { throw IOException("offline") })         val viewModel = NewsViewModel(context, repository, NewsPrefs(context))         var opened = 0         rule.setContent {