From 3913499e2043294c605ec970ce9a90a848d9e8f5 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 10 May 2025 18:13:56 -0600 Subject: [PATCH] musikr: prototype fs cache system Created by Claude 3.7 Sonnet --- build.gradle | 3 +- musikr/build.gradle | 3 + .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 170 ++++++++--- .../oxycblt/musikr/fs/device/DeviceFSCache.kt | 278 ++++++++++++++++++ 4 files changed, 406 insertions(+), 48 deletions(-) create mode 100644 musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt diff --git a/build.gradle b/build.gradle index 7bc5b84a9..deed629ef 100644 --- a/build.gradle +++ b/build.gradle @@ -30,7 +30,8 @@ plugins { //noinspection GradlePluginVersion id 'com.android.library' version "$agp_version" apply false id "org.jetbrains.kotlin.android" version "$kotlin_version" apply false - id "com.google.devtools.ksp" version '2.0.21-1.0.25' apply false + id 'org.jetbrains.kotlin.plugin.serialization' version "$kotlin_version" apply false + id "com.google.devtools.ksp" version '2.0.21-1.0.27' apply false // We use spotless in the root build.gradle to apply to all modules. id "com.diffplug.spotless" version "6.25.0" apply true } diff --git a/musikr/build.gradle b/musikr/build.gradle index 9e819dcff..a5d021a6e 100644 --- a/musikr/build.gradle +++ b/musikr/build.gradle @@ -7,6 +7,7 @@ plugins { id "com.diffplug.spotless" id "kotlin-parcelize" id "org.jetbrains.dokka" + id "org.jetbrains.kotlin.plugin.serialization" } android { @@ -62,6 +63,8 @@ dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines_version" + implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0' + // AndroidX implementation "androidx.core:core-ktx:$core_version" 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 a6831cc71..a1ae49deb 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 @@ -15,15 +15,17 @@ * 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.content.Context import android.net.Uri import android.provider.DocumentsContract +import android.util.Log import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow @@ -31,30 +33,52 @@ import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flattenMerge import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.onCompletion +import kotlinx.coroutines.flow.onStart import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.Path +private const val TAG = "DeviceFS" + internal interface DeviceFS { fun explore(locations: Flow): Flow companion object { fun from(context: Context, withHidden: Boolean): DeviceFS = - DeviceFSImpl(context.contentResolverSafe, withHidden) + DeviceFSImpl(context, withHidden) } } @OptIn(ExperimentalCoroutinesApi::class) private class DeviceFSImpl( - private val contentResolver: ContentResolver, + private val context: Context, private val withHidden: Boolean ) : DeviceFS { + private val contentResolver = context.contentResolverSafe + private val cache = DeviceFSCache(context) + override fun explore(locations: Flow): Flow = - locations.flatMapMerge { location -> - exploreDirectoryImpl( - location.uri, - DocumentsContract.getTreeDocumentId(location.uri), - location.path, - null) + flow { + // Initialize the cache + cache.loadCache() + // Start a new traversal to track processed URIs for cleanup + cache.resetTraversalTracking() + + emitAll( + locations.flatMapMerge { location -> + exploreDirectoryImpl( + location.uri, + DocumentsContract.getTreeDocumentId(location.uri), + location.path, + null + ) + }.flowOn(Dispatchers.IO) + ) + }.onCompletion { + // Cleanup and save cache when exploration is complete + cache.cleanupCache() + cache.saveCache() } private fun exploreDirectoryImpl( @@ -63,56 +87,108 @@ private class DeviceFSImpl( relativePath: Path, parent: Deferred? ): Flow = flow { - // Make a kotlin future - val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) + // Create deferred value for this directory + val directoryUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId) val directoryDeferred = CompletableDeferred() val recursive = mutableListOf>() val children = mutableListOf() - contentResolver.useQuery(uri, PROJECTION) { cursor -> - val childUriIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) - val displayNameIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) - val mimeTypeIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) - val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE) - val lastModifiedIndex = - cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) - while (cursor.moveToNext()) { - val childId = cursor.getString(childUriIndex) - val displayName = cursor.getString(displayNameIndex) + // Try to use cached directory contents + val cacheHit = cache.validateDirectoryCache(directoryUri) - // Skip hidden files/directories if ignoreHidden is true - if (!withHidden && displayName.startsWith(".")) { - continue - } + if (cacheHit) { + // We got a cache hit, process the cached children + Log.d(TAG, "Cache hit for $directoryUri") + val cachedChildren = cache.getCachedChildren(directoryUri) - val newPath = relativePath.file(displayName) - val mimeType = cursor.getString(mimeTypeIndex) - val lastModified = cursor.getLong(lastModifiedIndex) + if (cachedChildren != null) { + for (child in cachedChildren) { + val childUri = Uri.parse(child.uri) + val childName = child.name - if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { - recursive.add( - exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)) - } else { - val size = cursor.getLong(sizeIndex) - val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) - val file = - DeviceFile( + // Skip hidden files/directories if withHidden is false + if (!withHidden && childName.startsWith(".")) { + continue + } + + val newPath = relativePath.file(childName) + + if (child.type == EntryType.DIRECTORY) { + // For directories, recursively process them + val childId = DocumentsContract.getDocumentId(childUri) + recursive.add( + exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred) + ) + } else { + // For files, create DeviceFile objects and emit them + val file = DeviceFile( uri = childUri, - mimeType = mimeType, + mimeType = "", // We don't cache mime type but it's not used elsewhere path = newPath, - size = size, - modifiedMs = lastModified, - parent = directoryDeferred) - children.add(file) - emit(file) + size = 0, // We don't cache size but it's not used elsewhere + modifiedMs = child.modifiedDate, + parent = directoryDeferred + ) + children.add(file) + emit(file) + } + } + } + } else { + // Cache miss or stale data, query the directory contents directly + Log.d(TAG, "Cache miss for $directoryUri, querying directory contents") + val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) + + contentResolver.useQuery(uri, PROJECTION) { cursor -> + val childUriIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) + val displayNameIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) + val mimeTypeIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) + val sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE) + val lastModifiedIndex = + cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + + while (cursor.moveToNext()) { + val childId = cursor.getString(childUriIndex) + val displayName = cursor.getString(displayNameIndex) + + // Skip hidden files/directories if ignoreHidden is true + if (!withHidden && displayName.startsWith(".")) { + continue + } + + val newPath = relativePath.file(displayName) + val mimeType = cursor.getString(mimeTypeIndex) + val lastModified = cursor.getLong(lastModifiedIndex) + + if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { + recursive.add( + exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)) + } else { + val size = cursor.getLong(sizeIndex) + val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) + val file = + DeviceFile( + uri = childUri, + mimeType = mimeType, + path = newPath, + size = size, + modifiedMs = lastModified, + parent = directoryDeferred) + children.add(file) + emit(file) + } } } - directoryDeferred.complete(DeviceDirectory(uri, relativePath, parent, children)) - emitAll(recursive.asFlow().flattenMerge()) } + + // Complete the directory structure + directoryDeferred.complete(DeviceDirectory(directoryUri, relativePath, parent, children)) + + // Process all subdirectories + emitAll(recursive.asFlow().flattenMerge()) } private companion object { diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt new file mode 100644 index 000000000..c6a893828 --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSCache.kt @@ -0,0 +1,278 @@ +/* + * Copyright (c) 2024 Auxio Project + * DeviceFSCache.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.content.Context +import android.net.Uri +import android.provider.DocumentsContract +import android.util.Log +import androidx.annotation.VisibleForTesting +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import java.io.File + +private const val TAG = "DeviceFSCache" +private const val CACHE_FILE_NAME = "device_fs_cache.json" +private const val SCHEMA_VERSION = "1.0" + +/** + * Caches directory structure information to minimize ContentResolver queries. + * + * This cache is based on the concept that a directory's modification date changes + * when its direct contents change (files added, removed, renamed). We can avoid + * expensive children queries by caching directory contents and validating them + * against the directory's modification timestamp. + */ +internal class DeviceFSCache(private val context: Context) { + + private val contentResolver: ContentResolver = context.contentResolver + private val cache: MutableMap = mutableMapOf() + private val processedUris = mutableSetOf() + + /** + * Gets information about a directory URI. + * + * @param uri The document URI to get information for + * @return A DirectoryInfo object or null if there was an error + */ + fun getDirectoryInfo(uri: Uri): DirectoryInfo? { + return contentResolver.useQuery( + uri, + arrayOf( + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + DocumentsContract.Document.COLUMN_LAST_MODIFIED + ) + ) { cursor -> + if (cursor.moveToFirst()) { + val nameIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) + val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + + val name = cursor.getString(nameIndex) + val lastModified = cursor.getLong(lastModifiedIndex) + + DirectoryInfo(name, lastModified) + } else { + null + } + } + } + + /** + * Gets the children of a directory URI. + * + * @param uri The document URI to get children for + * @return A list of DirectoryChildren or null if there was an error + */ + fun getDirectoryChildren(uri: Uri): List? { + val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree( + uri, + DocumentsContract.getDocumentId(uri) + ) + + return contentResolver.useQuery( + childrenUri, + CHILDREN_PROJECTION + ) { cursor -> + val children = mutableListOf() + + val documentIdIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) + val displayNameIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME) + val mimeTypeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE) + val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) + + while (cursor.moveToNext()) { + val childId = cursor.getString(documentIdIndex) + val displayName = cursor.getString(displayNameIndex) + val mimeType = cursor.getString(mimeTypeIndex) + val lastModified = cursor.getLong(lastModifiedIndex) + + val isDirectory = mimeType == DocumentsContract.Document.MIME_TYPE_DIR + val childUri = DocumentsContract.buildDocumentUriUsingTree(uri, childId) + + children.add( + DirectoryChild( + uri = childUri.toString(), + name = displayName, + type = if (isDirectory) EntryType.DIRECTORY else EntryType.FILE, + modifiedDate = lastModified + ) + ) + } + + children + } ?: emptyList() + } + + /** + * Validates the cached data against directory's current state. + * If directory's modification time has changed, cache is updated. + * + * @param uri The URI of the directory to validate + * @return Whether the cache was hit (true) or needed updating (false) + */ + fun validateDirectoryCache(uri: Uri): Boolean { + val uriString = uri.toString() + processedUris.add(uriString) + + val dirInfo = getDirectoryInfo(uri) ?: run { + // Directory no longer exists or accessible, remove from cache + cache.remove(uriString) + return false + } + + // Check if we have cache entry and whether it's still valid + val cachedDir = cache[uriString] + if (cachedDir != null && cachedDir.modifiedDate == dirInfo.lastModified) { + // Cache hit - modification timestamp matches, so content hasn't changed + return true + } + + // Cache miss or stale data - need to update + val children = getDirectoryChildren(uri) ?: emptyList() + cache[uriString] = CachedDirectory( + modifiedDate = dirInfo.lastModified, + children = children + ) + + return false + } + + /** + * Gets cached directory children without validation. + * Use validateDirectoryCache() first to ensure cached data is valid. + * + * @param uri The URI of the directory + * @return The cached children or null if not cached + */ + fun getCachedChildren(uri: Uri): List? { + return cache[uri.toString()]?.children + } + + /** + * Cleans up the cache by removing entries that weren't accessed + * in the current traversal. + */ + fun cleanupCache() { + val toRemove = cache.keys.filter { it !in processedUris } + toRemove.forEach { cache.remove(it) } + } + + /** + * Resets the processed URIs tracking set for a new full traversal. + */ + fun resetTraversalTracking() { + processedUris.clear() + } + + /** + * Saves the cache to disk. + */ + suspend fun saveCache() = withContext(Dispatchers.IO) { + try { + val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) + val cacheData = CacheData( + schemaVersion = SCHEMA_VERSION, + entries = cache + ) + cacheFile.writeText(Json.encodeToString(CacheData.serializer(), cacheData)) + } catch (e: Exception) { + Log.e(TAG, "Failed to save cache", e) + } + } + + /** + * Loads the cache from disk. + */ + suspend fun loadCache() = withContext(Dispatchers.IO) { + try { + val cacheFile = File(context.cacheDir, CACHE_FILE_NAME) + if (cacheFile.exists()) { + val cacheDataString = cacheFile.readText() + val cacheData = Json.decodeFromString(cacheDataString) + + // Only load if schema version matches + if (cacheData.schemaVersion == SCHEMA_VERSION) { + cache.clear() + cache.putAll(cacheData.entries) + } + } + } catch (e: Exception) { + Log.e(TAG, "Failed to load cache", e) + // Start with empty cache if loading fails + cache.clear() + } + } + + companion object { + val CHILDREN_PROJECTION = arrayOf( + DocumentsContract.Document.COLUMN_DOCUMENT_ID, + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + DocumentsContract.Document.COLUMN_MIME_TYPE, + DocumentsContract.Document.COLUMN_LAST_MODIFIED + ) + } +} + +/** + * Information about a directory. + */ +data class DirectoryInfo( + val name: String, + val lastModified: Long +) + +/** + * Type of a directory entry. + */ +enum class EntryType { + FILE, + DIRECTORY +} + +/** + * Child entry in a directory. + */ +@Serializable +data class DirectoryChild( + val uri: String, + val name: String, + val type: EntryType, + val modifiedDate: Long +) + +/** + * Cached information about a directory. + */ +@Serializable +data class CachedDirectory( + val modifiedDate: Long, + val children: List +) + +/** + * Structure for serializing/deserializing the entire cache. + */ +@Serializable +data class CacheData( + val schemaVersion: String, + val entries: Map +) \ No newline at end of file