From 5df6f9e623b07a1f558bceeaa1c6524f83ecc718 Mon Sep 17 00:00:00 2001 From: Jay Date: Sat, 14 Nov 2026 08:50:28 -0500 Subject: [PATCH] Coordinate snapshot restoration before indexing --- app/build.gradle | 2 + .../auxio/music/LibrarySnapshotRestore.kt | 131 +++++++++++ .../org/oxycblt/auxio/music/MusicModule.kt | 2 + .../oxycblt/auxio/music/MusicRepository.kt | 4 + .../LibrarySnapshotRestoreConcurrencyTest.kt | 208 ++++++++++++++++++ .../musikr/snapshot/LibrarySnapshot.kt | 25 ++- 6 files changed, 369 insertions(+), 3 deletions(-) create mode 100644 app/src/main/java/org/oxycblt/auxio/music/LibrarySnapshotRestore.kt create mode 100644 app/src/test/java/org/oxycblt/auxio/music/LibrarySnapshotRestoreConcurrencyTest.kt diff --git a/app/build.gradle b/app/build.gradle index bca1608b4..5f23763c4 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -93,6 +93,8 @@ kotlin { dependencies { testImplementation "junit:junit:4.13.2" + testImplementation "io.mockk:mockk:1.14.11" + testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$kotlin_coroutines_version" androidTestImplementation "androidx.test:runner:1.7.0" androidTestImplementation "androidx.test.ext:junit:1.3.0" diff --git a/app/src/main/java/org/oxycblt/auxio/music/LibrarySnapshotRestore.kt b/app/src/main/java/org/oxycblt/auxio/music/LibrarySnapshotRestore.kt new file mode 100644 index 000000000..b5e85d072 --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/music/LibrarySnapshotRestore.kt @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2026 Auxio Project + * LibrarySnapshotRestore.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.auxio.music + +import android.content.Context +import java.io.File +import javax.inject.Inject +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.CancellationException +import org.oxycblt.auxio.image.ImageSettings +import org.oxycblt.auxio.music.locations.LocationMode +import org.oxycblt.musikr.Interpretation +import org.oxycblt.musikr.MutableLibrary +import org.oxycblt.musikr.fs.mediastore.MediaStore.FilterMode +import org.oxycblt.musikr.playlist.db.StoredPlaylists +import org.oxycblt.musikr.snapshot.LibrarySnapshot +import org.oxycblt.musikr.snapshot.LibrarySnapshotFingerprint +import org.oxycblt.musikr.snapshot.LibrarySnapshotStore +import org.oxycblt.musikr.tag.interpret.Naming +import org.oxycblt.musikr.tag.interpret.Separators + +interface SnapshotRestoration { + suspend fun await(): MutableLibrary? +} + +class SharedSnapshotRestoration +internal constructor( + scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO), + restore: suspend () -> MutableLibrary?, +) : SnapshotRestoration { + private val deferred = scope.async { restore() } + + override suspend fun await(): MutableLibrary? { + return try { + deferred.await() + } catch (exception: CancellationException) { + throw exception + } catch (exception: Exception) { + null + } + } +} + +interface SnapshotRestorer { + fun start(): SnapshotRestoration +} + +class MusikrSnapshotRestorer +@Inject +constructor( + @dagger.hilt.android.qualifiers.ApplicationContext private val context: Context, + private val storedPlaylists: StoredPlaylists, + private val musicSettings: MusicSettings, + private val imageSettings: ImageSettings, +) : SnapshotRestorer { + override fun start(): SnapshotRestoration { + val interpretation = + Interpretation( + if (musicSettings.intelligentSorting) Naming.intelligent() else Naming.simple(), + Separators.from(musicSettings.separators), + ) + val fingerprint = fingerprint() + return SharedSnapshotRestoration { + LibrarySnapshot(context, storedPlaylists, interpretation) + .restore(LibrarySnapshotStore(context.filesDir), fingerprint) + } + } + + private fun fingerprint(): LibrarySnapshotFingerprint { + val sourceMode = musicSettings.locationMode + val sourceRoots: List + val excludedRoots: List + val withHidden: Boolean + val excludeNonMusic: Boolean + when (sourceMode) { + LocationMode.SAF -> { + val query = musicSettings.safQuery + sourceRoots = query.source.map { it.uri.toString() } + excludedRoots = query.exclude.map { it.uri.toString() } + withHidden = query.withHidden + excludeNonMusic = false + } + LocationMode.MEDIA_STORE -> { + val query = musicSettings.mediaStoreQuery + sourceRoots = + if (query.mode == FilterMode.INCLUDE) { + query.filtered.map { it.uri.toString() } + } else { + emptyList() + } + excludedRoots = + if (query.mode == FilterMode.EXCLUDE) { + query.filtered.map { it.uri.toString() } + } else { + emptyList() + } + withHidden = false + excludeNonMusic = query.excludeNonMusic + } + } + return LibrarySnapshotFingerprint( + sourceMode = sourceMode.name, + sourceRoots = sourceRoots, + excludedRoots = excludedRoots, + withHidden = withHidden, + excludeNonMusic = excludeNonMusic, + intelligentSorting = musicSettings.intelligentSorting, + separators = musicSettings.separators, + coverMode = imageSettings.coverMode.name, + ) + } +} diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicModule.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicModule.kt index b7e9d3b0d..091d3974d 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicModule.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicModule.kt @@ -30,4 +30,6 @@ interface MusicModule { @Singleton @Binds fun repository(musicRepository: MusicRepositoryImpl): MusicRepository @Binds fun settings(musicSettingsImpl: MusicSettingsImpl): MusicSettings + + @Binds fun snapshotRestorer(restorer: MusikrSnapshotRestorer): SnapshotRestorer } diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt index b2a42e6a6..aa704bad0 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt @@ -246,6 +246,7 @@ constructor( private val storedPlaylists: StoredPlaylists, private val settingCovers: SettingCovers, private val musicSettings: MusicSettings, + private val snapshotRestorer: SnapshotRestorer, ) : MusicRepository { private val updateListeners = mutableListOf() private val indexingListeners = mutableListOf() @@ -257,6 +258,8 @@ constructor( override val indexingState: IndexingState? get() = currentIndexingState ?: previousCompletedState + private val snapshotRestoration = snapshotRestorer.start() + @Synchronized override fun addUpdateListener(listener: MusicRepository.UpdateListener) { L.d("Adding $listener to update listeners") @@ -382,6 +385,7 @@ constructor( private suspend fun indexImpl(withCache: Boolean) { L.d("Index requested, initializing") + snapshotRestoration.await() // Obtain configuration information val separators = Separators.from(musicSettings.separators) L.d("Separators: $separators") diff --git a/app/src/test/java/org/oxycblt/auxio/music/LibrarySnapshotRestoreConcurrencyTest.kt b/app/src/test/java/org/oxycblt/auxio/music/LibrarySnapshotRestoreConcurrencyTest.kt new file mode 100644 index 000000000..85ffdb92e --- /dev/null +++ b/app/src/test/java/org/oxycblt/auxio/music/LibrarySnapshotRestoreConcurrencyTest.kt @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2026 Auxio Project + * LibrarySnapshotRestoreConcurrencyTest.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.auxio.music + +import io.mockk.coEvery +import io.mockk.every +import io.mockk.mockk +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicReference +import kotlin.coroutines.ContinuationInterceptor +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.oxycblt.auxio.image.covers.SettingCovers +import org.oxycblt.musikr.MutableLibrary + +@OptIn(ExperimentalCoroutinesApi::class) +class LibrarySnapshotRestoreConcurrencyTest { + @Before + fun installMainDispatcher() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @After + fun resetMainDispatcher() { + Dispatchers.resetMain() + } + + @Test + fun repositoryCreation_startsRestorationOffMain() { + val dispatcher = AtomicReference() + val restoration = + SharedSnapshotRestoration { + dispatcher.set(currentCoroutineContext()[ContinuationInterceptor]) + null + } + restorationsAwait(restoration) + assertSame(Dispatchers.IO, dispatcher.get()) + val restorer = TestSnapshotRestorer(restoration) + + repository(restorer) + + assertEquals(1, restorer.starts) + } + + @Test + fun repeatedIndexingCalls_shareOneRestorationAttempt() = runTest { + val attempts = AtomicInteger() + val scanCalls = AtomicInteger() + val started = CompletableDeferred() + val release = CompletableDeferred() + val restoration = + SharedSnapshotRestoration { + attempts.incrementAndGet() + started.complete(Unit) + release.await() + } + val restorer = TestSnapshotRestorer(restoration) + val repository = scanningRepository(restorer, scanCalls) + val worker = mockk() + + val first = async { repository.index(worker, withCache = true) } + val second = async { repository.index(worker, withCache = true) } + started.await() + assertEquals(0, scanCalls.get()) + + release.complete(null) + first.await() + second.await() + + assertEquals(1, attempts.get()) + assertEquals(1, restorer.starts) + } + + @Test + fun indexing_awaitsRestorationBeforeReadingIndexConfiguration() = runTest { + val entered = CompletableDeferred() + val release = CompletableDeferred() + val restoration = + object : SnapshotRestoration { + override suspend fun await(): MutableLibrary? { + entered.complete(Unit) + return release.await() + } + } + val scanCalls = AtomicInteger() + val repository = scanningRepository(TestSnapshotRestorer(restoration), scanCalls) + val worker = mockk() + + val indexing = async { repository.index(worker, withCache = true) } + entered.await() + assertEquals(0, scanCalls.get()) + + release.complete(null) + indexing.await() + + assertEquals(1, scanCalls.get()) + } + + @Test + fun cancellingIndexing_doesNotCancelIndependentRestoration() = runTest { + val attempts = AtomicInteger() + val finished = AtomicBoolean() + val started = CompletableDeferred() + val release = CompletableDeferred() + val restoration = + SharedSnapshotRestoration { + attempts.incrementAndGet() + started.complete(Unit) + release.await() + finished.set(true) + null + } + val scanCalls = AtomicInteger() + val repository = scanningRepository(TestSnapshotRestorer(restoration), scanCalls) + val worker = mockk() + + val indexing = async { repository.index(worker, withCache = true) } + started.await() + indexing.cancel() + indexing.join() + + assertTrue(indexing.isCancelled) + assertEquals(0, scanCalls.get()) + assertFalse(finished.get()) + + release.complete(null) + restoration.await() + + assertTrue(finished.get()) + assertEquals(1, attempts.get()) + } + + private fun scanningRepository( + restorer: SnapshotRestorer, + scanCalls: AtomicInteger, + ): MusicRepositoryImpl { + val settings = mockk() + every { settings.separators } answers { + scanCalls.incrementAndGet() + "" + } + every { settings.intelligentSorting } returns true + every { settings.revision } returns null + every { settings.useFileTreeCache } returns false + val covers = mockk() + coEvery { covers.mutate(any(), any()) } throws + IllegalStateException("Expected test indexing boundary") + return MusicRepositoryImpl(mockk(), mockk(), mockk(), covers, settings, restorer) + } + + private fun restorationsAwait(restoration: SnapshotRestoration) { + runBlocking { restoration.await() } + } + + private fun repository(restorer: SnapshotRestorer) = + MusicRepositoryImpl( + mockk(), + mockk(), + mockk(), + mockk(), + mockk(), + restorer, + ) + + private class TestSnapshotRestorer( + private val restoration: SnapshotRestoration + ) : SnapshotRestorer { + var starts = 0 + private set + + override fun start(): SnapshotRestoration { + starts += 1 + return restoration + } + } +} diff --git a/musikr/src/main/java/org/oxycblt/musikr/snapshot/LibrarySnapshot.kt b/musikr/src/main/java/org/oxycblt/musikr/snapshot/LibrarySnapshot.kt index a28f1e9ad..2b5e8e129 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/snapshot/LibrarySnapshot.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/snapshot/LibrarySnapshot.kt @@ -22,6 +22,7 @@ import android.content.Context import java.io.File import java.io.InputStream import org.oxycblt.musikr.Config +import org.oxycblt.musikr.Interpretation import org.oxycblt.musikr.Library import org.oxycblt.musikr.MutableLibrary import org.oxycblt.musikr.model.SongImpl @@ -29,10 +30,28 @@ import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.playlist.interpret.PlaylistInterpreter import org.oxycblt.musikr.tag.interpret.PreSong -class LibrarySnapshot(private val context: Context, config: Config) { +class LibrarySnapshot +private constructor( + private val context: Context, + private val storedPlaylists: StoredPlaylists, + private val playlistInterpreter: PlaylistInterpreter, +) { + constructor( + context: Context, + config: Config, + ) : this( + context, + config.storage.storedPlaylists, + PlaylistInterpreter.new(config.interpretation), + ) + + constructor( + context: Context, + storedPlaylists: StoredPlaylists, + interpretation: Interpretation, + ) : this(context, storedPlaylists, PlaylistInterpreter.new(interpretation)) + private val storedCoverDirectory = File(context.filesDir, "covers") - private val storedPlaylists: StoredPlaylists = config.storage.storedPlaylists - private val playlistInterpreter = PlaylistInterpreter.new(config.interpretation) suspend fun capture( library: Library,