musikr.cache: bulk read cache into memory

I didn't want to do this, but it's just faster than before.
This commit is contained in:
Alexander Capehart
2025-05-15 17:00:21 -06:00
parent ab906ce286
commit 22d43e5849
2 changed files with 18 additions and 1 deletions
@@ -55,6 +55,8 @@ internal abstract class CacheDatabase : RoomDatabase() {
internal interface CacheReadDao {
@Query("SELECT * FROM CachedSongData WHERE uri = :uri")
suspend fun selectSong(uri: String): CachedSongData?
@Query("SELECT * FROM CachedSongData") suspend fun selectAllSongs(): List<CachedSongData>
}
@Dao
+16 -1
View File
@@ -19,6 +19,9 @@
package org.oxycblt.musikr.cache.db
import android.content.Context
import android.net.Uri
import android.util.Log
import kotlinx.coroutines.sync.Mutex
import org.oxycblt.musikr.cache.Cache
import org.oxycblt.musikr.cache.CacheResult
import org.oxycblt.musikr.cache.CachedSong
@@ -33,8 +36,20 @@ import org.oxycblt.musikr.tag.parse.ParsedTags
* Create an instance with [from].
*/
class DBCache private constructor(private val readDao: CacheReadDao) : Cache {
@Volatile private var mapping: MutableMap<Uri, CachedSongData>? = null
private var mappingLock = Mutex()
override suspend fun read(file: DeviceFile): CacheResult {
val dbSong = readDao.selectSong(file.uri.toString()) ?: return CacheResult.Miss(file)
mappingLock.lock()
val mapping =
this.mapping
?: readDao
.selectAllSongs()
.associateBy { it.uri }
.toMutableMap()
.also { mapping = it }
mappingLock.unlock()
val dbSong = mapping[file.uri] ?: return CacheResult.Miss(file)
if (dbSong.modifiedMs != file.modifiedMs) {
return CacheResult.Stale(file, dbSong.addedMs)
}