Modern Apps git

← Modern-Apps.git

musicbrainz: speed up browse screens and cover art loading

Commit
04315de45c45fd9b1c17b1e103164cb5b3f2a5c1
Author
vayun-mathur <[email protected]>
When
2026-08-21 20:04 UTC (3 months ago)
Parents
bea2be9

Diff

musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.ktindex d2f26f0edd..ec01b3f1e9 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt@@ -76,15 +76,24 @@ object MusicBrainzApi {     internal fun waitBeforeSending(now: Long, sentAt: Long): Long =         (MIN_REQUEST_SPACING_MS - (now - sentAt)).coerceAtLeast(0L) -    /** Serialises requests and spaces them out so the shared rate limit is respected. */-    private suspend fun <T> gate(block: suspend () -> T): T = rateLimit.withLock {-        delay(waitBeforeSending(System.currentTimeMillis(), lastRequestAt))-        // Stamped before the call rather than after it. The limit is on how often requests are-        // SENT, so the cooldown belongs alongside the round trip, not after it: stamping on-        // completion charged every caller the spacing PLUS the latency, which roughly doubled-        // the cost of each request and made a two-request screen take seconds.-        lastRequestAt = System.currentTimeMillis()-        block()+    /**+     * Spaces requests out so the shared rate limit is respected.+     *+     * The lock covers only the wait and the stamp, not the round trip. The limit is on how+     * often requests are SENT, so once a caller has claimed its slot the next one can start+     * waiting for its own; holding the lock across `block()` charged every caller the spacing+     * PLUS the latency of the request ahead of it, which serialised the deliberately+     * overlapped `async` pairs in the view model and made a two-request screen cost seconds.+     *+     * Stamped before the call rather than after it, for the same reason: the cooldown belongs+     * alongside the round trip, not after it.+     */+    private suspend fun <T> gate(block: suspend () -> T): T {+        rateLimit.withLock {+            delay(waitBeforeSending(System.currentTimeMillis(), lastRequestAt))+            lastRequestAt = System.currentTimeMillis()+        }+        return block()     }      private suspend inline fun <reified T> get(path: String): T = gate {
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/components/CoverArtImage.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/components/CoverArtImage.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/components/CoverArtImage.ktindex 4f1786bd7d..899c24c2b3 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/components/CoverArtImage.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/components/CoverArtImage.kt@@ -12,8 +12,11 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.unit.dp+import com.vayunmathur.library.image.ImageRequest import com.vayunmathur.library.image.compose.AsyncImage import com.vayunmathur.library.image.compose.AsyncImageState import com.vayunmathur.library.ui.IconAlbum@@ -31,6 +34,13 @@ import com.vayunmathur.library.ui.Surface  * failed load the [fallbackUrl] - the release-group cover - is tried before giving up.  * This mirrors the ordered list [com.vayunmathur.musicbrainz.platform.download.DownloadWorker]  * embeds from, so the in-app image matches what a download would carry.+ *+ * Two things keep this cheap enough to scroll. The request carries the display size, so a+ * 500 px archive JPEG is downsampled while decoding instead of landing on the heap at ~1 MB+ * a row. And a URL that recently failed is remembered in [CoverArtFailures]: the loader+ * caches successes but not failures, and a row leaving the viewport disposes its load, so+ * without that memory every scroll pass re-ran the whole redirect chain for art that is not+ * there.  */ @Composable fun CoverArtImage(@@ -47,23 +57,77 @@ fun CoverArtImage(             IconAlbum(tint = MaterialTheme.colorScheme.onSurfaceVariant)             // Previews render without a network, and the loader would just log failures.             if (url != null && !LocalInspectionMode.current) {-                var model by remember(url, fallbackUrl) { mutableStateOf(url) }-                AsyncImage(-                    model = model,-                    contentDescription = null,-                    modifier = Modifier.size(size.dp),-                    contentScale = ContentScale.Crop,-                    onState = { state ->-                        if (state is AsyncImageState.Error &&-                            model == url &&-                            fallbackUrl != null &&-                            fallbackUrl != url-                        ) {-                            model = fallbackUrl-                        }-                    },-                )+                val context = LocalContext.current+                val sizePx = with(LocalDensity.current) { size.dp.roundToPx() }+                var model by remember(url, fallbackUrl) {+                    mutableStateOf(CoverArtFailures.firstUntried(url, fallbackUrl))+                }+                val request = remember(model, sizePx, context) {+                    model?.let { ImageRequest.Builder(context).data(it).size(sizePx).build() }+                }+                if (request != null) {+                    AsyncImage(+                        model = request,+                        contentDescription = null,+                        modifier = Modifier.size(size.dp),+                        contentScale = ContentScale.Crop,+                        onState = { state ->+                            if (state is AsyncImageState.Error) {+                                val attempted = model+                                if (attempted != null) CoverArtFailures.record(attempted)+                                model = if (attempted == url) {+                                    fallbackUrl?.takeIf {+                                        it != url && !CoverArtFailures.hasFailed(it)+                                    }+                                } else {+                                    null+                                }+                            }+                        },+                    )+                }             }         }     } }++/**+ * The cover-art URLs recently found to have no image behind them.+ *+ * The Cover Art Archive 404s for a large share of releases, and the loader stores only+ * successes, so a failed load is free to repeat itself forever.+ *+ * Entries expire because the loader discards the HTTP status - a 404 and a dropped+ * connection both surface as a plain fetch failure - so this cannot tell "there is no art"+ * from "the network is down right now". A TTL keeps a real miss suppressed long enough to+ * make scrolling cheap while letting a spell offline heal itself. Bounded and LRU because+ * the miss set grows with everything the user browses.+ */+private object CoverArtFailures {++    private const val MAX_ENTRIES = 512+    private const val TTL_MS = 10 * 60 * 1000L++    private val failedAt = object : LinkedHashMap<String, Long>(64, 0.75f, true) {+        override fun removeEldestEntry(eldest: Map.Entry<String, Long>): Boolean =+            size > MAX_ENTRIES+    }++    fun hasFailed(url: String): Boolean = synchronized(failedAt) { isFresh(url) }++    fun record(url: String) {+        synchronized(failedAt) { failedAt[url] = System.currentTimeMillis() }+    }++    /** The first of [url] then [fallbackUrl] not known to fail, or null when both do. */+    fun firstUntried(url: String, fallbackUrl: String?): String? = synchronized(failedAt) {+        listOfNotNull(url, fallbackUrl).firstOrNull { !isFresh(it) }+    }++    private fun isFresh(url: String): Boolean {+        val at = failedAt[url] ?: return false+        if (System.currentTimeMillis() - at < TTL_MS) return true+        failedAt.remove(url)+        return false+    }+}