From 078718fadbe59b54c9cc670ff4980fc428a2be97 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sun, 1 Jun 2025 19:33:13 -0600 Subject: [PATCH] musikr: implement contentresolver ratelimits 1000 queries per second is probably slower than the prior max speed but is sadly required. --- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 5 +- .../oxycblt/musikr/fs/device/FileTreeCache.kt | 2 - .../org/oxycblt/musikr/fs/device/QueryUtil.kt | 11 +- .../fs/device/RateLimitedContentResolver.kt | 121 ++++++++++++++++++ 4 files changed, 133 insertions(+), 6 deletions(-) create mode 100644 musikr/src/main/java/org/oxycblt/musikr/fs/device/RateLimitedContentResolver.kt diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index 55e36ecce..07a4b0796 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -18,7 +18,6 @@ package org.oxycblt.musikr.fs.device -import android.content.ContentResolver import android.content.Context import android.net.Uri import android.provider.DocumentsContract @@ -52,12 +51,12 @@ internal interface DeviceFS { companion object { fun from(context: Context, withHidden: Boolean): DeviceFS = - DeviceFSImpl(context.contentResolverSafe, withHidden) + DeviceFSImpl(context.rateLimitedContentResolver, withHidden) } } private class DeviceFSImpl( - private val contentResolver: ContentResolver, + private val contentResolver: RateLimitedContentResolver, private val withHidden: Boolean ) : DeviceFS { private val explorationScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt index 210f8d4a5..c33b8efcb 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt @@ -25,8 +25,6 @@ import java.io.File import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable -import kotlinx.serialization.decodeFromString -import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import kotlinx.serialization.json.decodeFromStream import kotlinx.serialization.json.encodeToStream diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt index 15324c150..c1736e8db 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt @@ -30,6 +30,15 @@ import android.net.Uri internal val Context.contentResolverSafe: ContentResolver get() = applicationContext.contentResolver +internal val Context.rateLimitedContentResolver: RateLimitedContentResolver + get() = + RateLimitedContentResolver( + contentResolver = contentResolverSafe, + maxTokens = 100, // Maximum burst capacity + refillRate = 1000.0, // 1000 queries per second (100 queries per 100ms) + maxConcurrency = 10 // Maximum concurrent queries + ) + /** * A shortcut for querying the [ContentResolver] database. * @@ -74,4 +83,4 @@ internal inline fun ContentResolver.useQuery( args: Array? = null, sortOrder: String? = null, block: (Cursor) -> R -) = query(uri, projection, selector, args, sortOrder)?.use(block) +) = safeQuery(uri, projection, selector, args, sortOrder).use(block) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/RateLimitedContentResolver.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/RateLimitedContentResolver.kt new file mode 100644 index 000000000..548c139c4 --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/RateLimitedContentResolver.kt @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2024 Auxio Project + * RateLimitedContentResolver.kt is part of Auxio. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.oxycblt.musikr.fs.device + +import android.content.ContentResolver +import android.database.Cursor +import android.net.Uri +import kotlin.math.min +import kotlinx.coroutines.delay +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.Semaphore +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.sync.withPermit + +/** + * A rate-limited wrapper around ContentResolver that uses a token bucket algorithm to limit the + * rate of queries. + * + * @param contentResolver The underlying ContentResolver to wrap + * @param maxTokens The maximum number of tokens in the bucket (burst capacity) + * @param refillRate The rate at which tokens are refilled per second + * @param maxConcurrency The maximum number of concurrent queries allowed + */ +internal class RateLimitedContentResolver( + private val contentResolver: ContentResolver, + private val maxTokens: Int = 1000, + private val refillRate: Double = 1000.0, // tokens per second + private val maxConcurrency: Int = 10 +) { + private val tokenBucket = TokenBucket(maxTokens, refillRate) + private val concurrencySemaphore = Semaphore(maxConcurrency) + + /** + * A rate-limited version of ContentResolver.query This is a suspend function that should be + * called from a coroutine + */ + suspend fun query( + uri: Uri, + projection: Array?, + selection: String?, + selectionArgs: Array?, + sortOrder: String? + ): Cursor? = + concurrencySemaphore.withPermit { + tokenBucket.acquire() + contentResolver.query(uri, projection, selection, selectionArgs, sortOrder) + } + + /** + * A shortcut for querying the database with automatic resource management. Rate-limited version + * of the useQuery extension function. This is a suspend function that should be called from a + * coroutine + */ + suspend inline fun useQuery( + uri: Uri, + projection: Array, + selector: String? = null, + args: Array? = null, + sortOrder: String? = null, + crossinline block: suspend (Cursor) -> R + ): R = + concurrencySemaphore.withPermit { + tokenBucket.acquire() + contentResolver.useQuery(uri, projection, selector, args, sortOrder) { cursor -> + block(cursor) + } + } + + /** Token bucket implementation for rate limiting */ + internal class TokenBucket( + private val maxTokens: Int, + private val refillRate: Double // tokens per second + ) { + private var tokens: Double = maxTokens.toDouble() + private var lastRefillTime: Long = System.currentTimeMillis() + private val mutex = Mutex() + private val tokenWaitTime = (1000.0 / refillRate).toLong() // milliseconds per token + + suspend fun acquire() { + mutex.withLock { + refill() + + // Wait until a token is available + while (tokens < 1.0) { + val waitTime = ((1.0 - tokens) * tokenWaitTime).toLong() + delay(waitTime) + refill() + } + + tokens -= 1.0 + } + } + + private fun refill() { + val now = System.currentTimeMillis() + val timePassed = now - lastRefillTime + val tokensToAdd = (timePassed / 1000.0) * refillRate + + if (tokensToAdd > 0) { + tokens = min(tokens + tokensToAdd, maxTokens.toDouble()) + lastRefillTime = now + } + } + } +}