diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthStore.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthStore.kt index a525116b..f4f5e1ce 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthStore.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthStore.kt @@ -88,6 +88,17 @@ class AuthStore @Inject constructor( private val backgroundDeliveryState = MutableStateFlow(true) val backgroundDelivery: StateFlow = backgroundDeliveryState.asStateFlow() + // The account the cached data belongs to (AuthSessionEntity.cacheOwnerUserId). + // Null while the stored row is still loading, and before any account + // has been adopted; [settingsLoaded] tells the two apart. + private val cacheOwnerState = MutableStateFlow(null) + val cacheOwnerUserId: StateFlow = cacheOwnerState.asStateFlow() + + private val settingsLoadedState = MutableStateFlow(false) + + /** True once the stored settings row has been read at least once. */ + val settingsLoaded: StateFlow = settingsLoadedState.asStateFlow() + private val json = Json { ignoreUnknownKeys = true } // Serialises every cookie persist with the one-time hydration, so a @@ -112,6 +123,8 @@ class AuthStore @Inject constructor( diagnosticsOptOutState.value = row?.diagnosticsOptOut ?: false normalizationState.value = decodeNormalization(row?.normalizationJson) backgroundDeliveryState.value = row?.backgroundDelivery ?: true + cacheOwnerState.value = row?.cacheOwnerUserId + settingsLoadedState.value = true } } } @@ -267,6 +280,25 @@ class AuthStore @Inject constructor( } } + /** + * Records which account the cached data now belongs to. Suspends until + * it is stored, so a caller that has just cleared the old account's + * data can't have the adoption lost to a crash in between. + */ + suspend fun setCacheOwnerUserId(value: String?) { + cacheOwnerState.value = value + if (dao.get() == null) { + dao.upsert(currentEntity().copy(cacheOwnerUserId = value)) + } else { + dao.setCacheOwnerUserId(value) + } + } + + /** Forgets the newest notice announced, so the next account starts fresh. */ + suspend fun clearNotifiedUpTo() { + if (dao.get() != null) dao.setNotifiedUpTo(null) + } + private suspend fun persistLegacyCookie(value: String?) { if (dao.get() == null) { dao.upsert(currentEntity().copy(sessionCookie = value)) @@ -350,6 +382,7 @@ class AuthStore @Inject constructor( normalizationState.value, ), backgroundDelivery = backgroundDeliveryState.value, + cacheOwnerUserId = cacheOwnerState.value, ) companion object { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountCache.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountCache.kt new file mode 100644 index 00000000..b7bd0bdd --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountCache.kt @@ -0,0 +1,109 @@ +package com.fabledsword.minstrel.cache.account + +import com.fabledsword.minstrel.auth.AuthController +import com.fabledsword.minstrel.auth.AuthStore +import com.fabledsword.minstrel.di.ApplicationScope +import com.fabledsword.minstrel.player.PlayerController +import dagger.Lazy +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.launch +import timber.log.Timber +import javax.inject.Inject +import javax.inject.Singleton + +/** What [AccountCache] does about the signed-in account and the cache's owner. */ +internal enum class OwnerStep { + /** Nobody is signed in, or the stored owner hasn't loaded yet. */ + WAIT, + + /** + * The cache has no owner yet (a fresh install, or one updated from + * before owners): adopt the account, keeping the data. + */ + ADOPT, + + /** Another account's data is cached: clear it, then adopt this account. */ + SWITCH, + + /** The signed-in account owns the cache. */ + OWNED, +} + +internal fun ownerStep(loaded: Boolean, signedInUserId: String?, ownerUserId: String?): OwnerStep = when { + !loaded || signedInUserId == null -> OwnerStep.WAIT + ownerUserId == null -> OwnerStep.ADOPT + ownerUserId != signedInUserId -> OwnerStep.SWITCH + else -> OwnerStep.OWNED +} + +/** + * Keeps one account's cached data from reaching another account on a + * shared device. + * + * The device caches data that belongs to whoever is signed in: their + * queued offline writes (likes, plays, quarantine flags, playlist adds, + * settings), Home, history, quarantine list, notifications and the queue + * the player resumes. Likes and playlists carry a user id of their own; + * these don't. So the cache has an owner, stored with the device's + * settings. When a different account signs in, that data is cleared and + * the player emptied before the new account is adopted, however the last + * one left: by signing out, or by the server refusing its session. + * + * The same person signing back in keeps everything, queued writes + * included, so a session that expires offline loses nothing. + * + * [ownedBySignedInUser] gates the offline-write replayer: queued writes + * are sent only while their owner is the one signed in, so they never go + * out under another account's session. + */ +@Singleton +class AccountCache @Inject constructor( + private val authStore: AuthStore, + authController: AuthController, + private val tables: AccountTables, + private val player: Lazy, + @ApplicationScope scope: CoroutineScope, +) { + private val ownedState = MutableStateFlow(false) + + /** True while the signed-in account is the one the cached data belongs to. */ + val ownedBySignedInUser: StateFlow = ownedState.asStateFlow() + + init { + scope.launch { + combine( + authStore.settingsLoaded, + authController.currentUser, + authStore.cacheOwnerUserId, + ) { loaded, user, owner -> Triple(loaded, user?.id, owner) } + .distinctUntilChanged() + .collect { (loaded, userId, owner) -> step(ownerStep(loaded, userId, owner), userId) } + } + } + + private suspend fun step(step: OwnerStep, userId: String?) { + when (step) { + OwnerStep.WAIT -> ownedState.value = false + // The stored owner changes next, and that emission reports OWNED. + OwnerStep.ADOPT -> authStore.setCacheOwnerUserId(userId) + OwnerStep.SWITCH -> { + ownedState.value = false + clearAccountData() + authStore.setCacheOwnerUserId(userId) + } + OwnerStep.OWNED -> ownedState.value = true + } + } + + private suspend fun clearAccountData() { + Timber.i("account cache: another account signed in; clearing the last one's data") + tables.clear() + authStore.clearNotifiedUpTo() + player.get().clearQueue() + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountTables.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountTables.kt new file mode 100644 index 00000000..164ee0c8 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountTables.kt @@ -0,0 +1,28 @@ +package com.fabledsword.minstrel.cache.account + +import androidx.room.withTransaction +import com.fabledsword.minstrel.cache.db.AppDatabase +import javax.inject.Inject +import javax.inject.Singleton + +/** + * The cached tables that hold one account's data and carry no user id of + * their own, cleared together by [AccountCache] when another account signs + * in. A new table of that kind belongs in [clear]; one keyed by user id + * (likes, playlists) or shared by every account (the library) does not. + */ +@Singleton +class AccountTables @Inject constructor(private val db: AppDatabase) { + /** Clears them in one transaction, so a crash can't leave half of them. */ + suspend fun clear() { + db.withTransaction { + db.cachedMutationDao().clear() + db.cachedHomeIndexDao().clear() + db.cachedHistorySnapshotDao().clear() + db.cachedQuarantineDao().clear() + db.cachedResumeStateDao().clear() + db.cachedNotificationDao().clear() + db.cachedNotificationDao().clearSettings() + } + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/AppDatabase.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/AppDatabase.kt index e6f2f0c9..c11d1c14 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/AppDatabase.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/AppDatabase.kt @@ -67,6 +67,9 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity CachedNotificationEntity::class, CachedNotificationSettingsEntity::class, ], + // v15: + auth_session.cacheOwnerUserId, the account the cached data + // belongs to. MIGRATION_14_15 adds it empty; AccountCache adopts the + // signed-in account. // v14: + cached_playlists.shelfRank, a system mix's place on its Home // shelf. MIGRATION_13_14 adds it as 0; the next list refresh fills it. // v13: + cached_playlists.coverAlbumIds and createdAt, the albums Home's @@ -92,7 +95,7 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity // on auth_session. Versions before v8 rebuild destructively, which is // right for them: the next sync refills every row with the new // columns populated, so there is nothing to migrate by hand. - version = 14, + version = 15, exportSchema = true, ) @TypeConverters(MinstrelTypeConverters::class) @@ -188,3 +191,14 @@ val MIGRATION_13_14: Migration = object : Migration(13, 14) { db.execSQL("ALTER TABLE cached_playlists ADD COLUMN shelfRank INTEGER NOT NULL DEFAULT 0") } } + +/** + * v14 → v15: the account the cached data belongs to. Starts empty, and + * AccountCache adopts whoever is signed in without clearing anything, so + * an update keeps the signed-in person's queued writes and cache. + */ +val MIGRATION_14_15: Migration = object : Migration(14, 15) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE auth_session ADD COLUMN cacheOwnerUserId TEXT") + } +} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/DatabaseModule.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/DatabaseModule.kt index 794f5181..506161f9 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/DatabaseModule.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/DatabaseModule.kt @@ -44,6 +44,7 @@ object DatabaseModule { MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, + MIGRATION_14_15, ) .fallbackToDestructiveMigration(dropAllTables = true) .build() diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/AuthSessionDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/AuthSessionDao.kt index d5b6f245..1e4b4ca8 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/AuthSessionDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/AuthSessionDao.kt @@ -59,4 +59,7 @@ interface AuthSessionDao { /** Partial update: change only the shade's high-water mark. */ @Query("UPDATE auth_session SET notifiedUpTo = :upTo WHERE id = 0") suspend fun setNotifiedUpTo(upTo: Instant?) + + @Query("UPDATE auth_session SET cacheOwnerUserId = :userId WHERE id = 0") + suspend fun setCacheOwnerUserId(userId: String?) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedHistorySnapshotDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedHistorySnapshotDao.kt index 737a2729..0d4e6b20 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedHistorySnapshotDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedHistorySnapshotDao.kt @@ -15,4 +15,7 @@ interface CachedHistorySnapshotDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsert(row: CachedHistorySnapshotEntity) + + @Query("DELETE FROM cached_history_snapshot") + suspend fun clear() } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedNotificationDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedNotificationDao.kt index 71f37b13..e13cc24d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedNotificationDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedNotificationDao.kt @@ -48,4 +48,7 @@ interface CachedNotificationDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertSettings(row: CachedNotificationSettingsEntity) + + @Query("DELETE FROM cached_notification_settings") + suspend fun clearSettings() } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/AuthSessionEntity.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/AuthSessionEntity.kt index f769d926..15e05458 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/AuthSessionEntity.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/entities/AuthSessionEntity.kt @@ -61,7 +61,15 @@ data class AuthSessionEntity( /** * The newest notice this device has announced in the shade. A catch-up * announces only what is newer, so a reboot or a reconnect never - * re-announces a backlog. Cleared on sign-out. + * re-announces a backlog. Cleared when another account signs in. */ val notifiedUpTo: Instant? = null, + /** + * The account the device's cached data belongs to: its queued offline + * writes, Home, history, quarantine list, notifications and resume + * queue. When a different account signs in, AccountCache clears that + * data before adopting the new account, so one person never sees or + * sends another's. Null until an account has been adopted. + */ + val cacheOwnerUserId: String? = null, ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationReplayer.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationReplayer.kt index 7c11eba9..3d904359 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationReplayer.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationReplayer.kt @@ -19,6 +19,7 @@ import com.fabledsword.minstrel.connectivity.ServerHealth import com.fabledsword.minstrel.models.wire.PlayEndedRequest import com.fabledsword.minstrel.models.wire.PlayOfflineRequest import com.fabledsword.minstrel.auth.AuthStore +import com.fabledsword.minstrel.cache.account.AccountCache import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity import com.fabledsword.minstrel.di.ApplicationScope @@ -52,10 +53,16 @@ import javax.inject.Singleton * - RETRY — transient (transport, 5xx, 408, 429) → leave queued, bump * attempts, retry on the next trigger. * + * Queued writes belong to the account that made them, and are sent only + * while [AccountCache] reports that account is the one signed in; when + * another account signs in, AccountCache clears them instead. + * * Triggered by: * - app start (MinstrelApplication @Inject forces the singleton's init) * - AuthStore.sessionCookie transitioning to non-null (sign-in / cold * start with a persisted cookie) + * - AccountCache confirming the signed-in account owns the queue (just + * after a sign-in, once the account is known) * - NetworkStatusController recovering to Healthy (server reachable again * mid-session — covers offline→online without needing a cold start) * @@ -68,6 +75,7 @@ import javax.inject.Singleton class MutationReplayer @Inject constructor( private val dao: CachedMutationDao, private val authStore: AuthStore, + private val accountCache: AccountCache, private val json: Json, @ApplicationScope private val scope: CoroutineScope, networkStatus: NetworkStatusController, @@ -92,6 +100,11 @@ class MutationReplayer @Inject constructor( .distinctUntilChanged() .collect { drainSafe() } } + scope.launch { + accountCache.ownedBySignedInUser + .filter { it } + .collect { drainSafe() } + } // Server-reachable-again: replay queued writes the moment the // health signal recovers, so an offline→online transition mid- // session doesn't wait for the next cold start / re-auth. @@ -115,6 +128,8 @@ class MutationReplayer @Inject constructor( } private suspend fun drain() { + // Another account's writes must not go out under this session. + if (!accountCache.ownedBySignedInUser.value) return val rows = dao.getAll() // Collapse superseded toggles (likes, settings): only the latest // desired state per entity is replayed; older toggles for the same diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerController.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerController.kt index 4ceb665f..fa9aef13 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerController.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerController.kt @@ -349,11 +349,13 @@ class PlayerController @Inject constructor( controller.removeMediaItem(index) } - /** Empty the queue and stop playback. */ + /** Empty the queue and stop playback. Safe to call from any thread. */ fun clearQueue() { val controller = mediaController ?: return - queueRefs = emptyList() - controller.clearMediaItems() + runOnControllerThread(controller) { + queueRefs = emptyList() + controller.clearMediaItems() + } } /** diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsViewModel.kt index 4de63638..41f104c9 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsViewModel.kt @@ -4,6 +4,7 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.fabledsword.minstrel.auth.AuthController import com.fabledsword.minstrel.auth.AuthStore +import com.fabledsword.minstrel.cache.mutations.MutationReplayer import com.fabledsword.minstrel.notifications.data.NotificationsRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow @@ -12,6 +13,7 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull import javax.inject.Inject data class SettingsState( @@ -30,6 +32,7 @@ class SettingsViewModel @Inject constructor( private val authController: AuthController, private val authStore: AuthStore, private val notifications: NotificationsRepository, + private val replayer: MutationReplayer, ) : ViewModel() { private val transient = MutableStateFlow(TransientState()) @@ -71,6 +74,10 @@ class SettingsViewModel @Inject constructor( if (transient.value.isSigningOut) return viewModelScope.launch { transient.update { it.copy(isSigningOut = true) } + // Send what is still queued while this session can: once another + // account signs in on this device, the rest is cleared unsent. + // Bounded, so signing out offline doesn't hang on the network. + withTimeoutOrNull(SIGN_OUT_DRAIN_MS) { runCatching { replayer.drainSafe() } } authController.signOut() // The inbox is this account's; the next one on the device must not see it. runCatching { notifications.clearLocal() } @@ -87,4 +94,11 @@ class SettingsViewModel @Inject constructor( val isSigningOut: Boolean = false, val signedOut: Boolean = false, ) + + private companion object { + // Long enough for a handful of queued writes on a working + // connection; short enough that a sign-out offline still feels + // immediate. + const val SIGN_OUT_DRAIN_MS = 5_000L + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/cache/account/AccountCacheTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/cache/account/AccountCacheTest.kt new file mode 100644 index 00000000..aef748af --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/cache/account/AccountCacheTest.kt @@ -0,0 +1,113 @@ +package com.fabledsword.minstrel.cache.account + +import com.fabledsword.minstrel.auth.AuthController +import com.fabledsword.minstrel.auth.AuthStore +import com.fabledsword.minstrel.models.UserRef +import com.fabledsword.minstrel.player.PlayerController +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import io.mockk.verify +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class OwnerStepTest { + @Test + fun `waits until the owner has loaded and someone is signed in`() { + assertEquals(OwnerStep.WAIT, ownerStep(loaded = false, signedInUserId = "a", ownerUserId = "a")) + assertEquals(OwnerStep.WAIT, ownerStep(loaded = true, signedInUserId = null, ownerUserId = "a")) + } + + @Test + fun `adopts the account when the cache has no owner, and clears another account's cache`() { + assertEquals(OwnerStep.ADOPT, ownerStep(loaded = true, signedInUserId = "a", ownerUserId = null)) + assertEquals(OwnerStep.SWITCH, ownerStep(loaded = true, signedInUserId = "b", ownerUserId = "a")) + assertEquals(OwnerStep.OWNED, ownerStep(loaded = true, signedInUserId = "a", ownerUserId = "a")) + } +} + +@OptIn(ExperimentalCoroutinesApi::class) +class AccountCacheTest { + private val loaded = MutableStateFlow(true) + private val user = MutableStateFlow(null) + private val owner = MutableStateFlow(null) + + private val authStore = mockk { + every { settingsLoaded } returns loaded + every { cacheOwnerUserId } returns owner + coEvery { setCacheOwnerUserId(any()) } coAnswers { owner.value = firstArg() } + coEvery { clearNotifiedUpTo() } returns Unit + } + private val authController = mockk { every { currentUser } returns user } + private val tables = mockk(relaxed = true) + private val player = mockk(relaxed = true) + + private fun TestScope.accountCache() = AccountCache( + authStore, authController, tables, { player }, TestScope(UnconfinedTestDispatcher(testScheduler)), + ) + + private fun signIn(id: String) { + user.value = UserRef(id = id, username = id, isAdmin = false) + } + + @Test + fun `another account signing in clears the last one's data before it owns the cache`() = runTest { + owner.value = "anna" + val cache = accountCache() + signIn("ben") + + coVerify(exactly = 1) { tables.clear() } + coVerify(exactly = 1) { authStore.clearNotifiedUpTo() } + verify(exactly = 1) { player.clearQueue() } + assertEquals("ben", owner.value) + assertTrue(cache.ownedBySignedInUser.value, "ben owns the cache once it is cleared") + } + + @Test + fun `the same account signing back in keeps everything, queued writes included`() = runTest { + owner.value = "anna" + val cache = accountCache() + signIn("anna") + user.value = null + assertFalse(cache.ownedBySignedInUser.value, "nobody owns it while signed out") + signIn("anna") + + coVerify(exactly = 0) { tables.clear() } + verify(exactly = 0) { player.clearQueue() } + assertTrue(cache.ownedBySignedInUser.value) + } + + @Test + fun `an install from before owners adopts the signed-in account without clearing`() = runTest { + val cache = accountCache() + signIn("anna") + + coVerify(exactly = 0) { tables.clear() } + assertEquals("anna", owner.value) + assertTrue(cache.ownedBySignedInUser.value) + } + + @Test + fun `nothing is owned until the stored owner has loaded`() = runTest { + loaded.value = false + owner.value = null + val cache = accountCache() + signIn("ben") + assertFalse(cache.ownedBySignedInUser.value) + coVerify(exactly = 0) { authStore.setCacheOwnerUserId(any()) } + + // The stored row arrives naming another account: that one's data goes. + owner.value = "anna" + loaded.value = true + coVerify(exactly = 1) { tables.clear() } + assertEquals("ben", owner.value) + } +} diff --git a/internal/tags/provider_artist_tags_test.go b/internal/tags/provider_artist_tags_test.go deleted file mode 100644 index 8d99c401..00000000 --- a/internal/tags/provider_artist_tags_test.go +++ /dev/null @@ -1,173 +0,0 @@ -package tags - -import ( - "context" - "errors" - "net/http" - "net/http/httptest" - "testing" -) - -// Artist-level tag fetching for out-of-library Discover candidates. -// Reuses the mbEntityServer / newMBProvider / newLastfmProvider helpers from -// the per-provider test files. - -func TestMusicBrainzFetchArtistTags_UsesFullWeightNotTheFallbackDiscount(t *testing.T) { - // THE distinction worth a test. artistTagWeightFactor (0.6) exists because - // FetchTrackTags uses artist tags as a *proxy* for a track's tags. Here the - // artist IS the subject, so weights must land unscaled — otherwise these - // are not comparable with track_tags, which is the comparison tag-space - // Discover is built on. - srv := mbEntityServer(``, `{"tags":[{"count":4,"name":"shoegaze"},{"count":2,"name":"dream pop"}]}`) - defer srv.Close() - old := mbBaseURL - mbBaseURL = srv.URL - defer func() { mbBaseURL = old }() - - tags, err := newMBProvider(true).FetchArtistTags(context.Background(), - ArtistRef{MBID: "art-1", Name: "Some Band"}) - if err != nil { - t.Fatalf("fetch: %v", err) - } - m := tagsByName(tags) - if got := m["shoegaze"]; got != 1.0 { - t.Errorf("shoegaze = %v, want 1.0 — not discounted by artistTagWeightFactor", got) - } - if got := m["dream pop"]; got != 0.5 { - t.Errorf("dream pop = %v, want 0.5", got) - } -} - -func TestMusicBrainzFetchArtistTags_GatedOff(t *testing.T) { - if _, err := newMBProvider(false).FetchArtistTags(context.Background(), - ArtistRef{MBID: "art-1"}); !errors.Is(err, ErrNotFound) { - t.Errorf("disabled: err = %v, want ErrNotFound", err) - } - // No MBID → nothing MusicBrainz can look up. A name-based guess could - // silently attach the wrong artist's tags, so it deliberately doesn't try. - if _, err := newMBProvider(true).FetchArtistTags(context.Background(), - ArtistRef{Name: "Some Band"}); !errors.Is(err, ErrNotFound) { - t.Errorf("no MBID: err = %v, want ErrNotFound", err) - } -} - -// fetchEntityTags reports an existing-but-untagged entity as (empty, nil) so -// FetchTrackTags can fall through to the artist level. FetchArtistTags has no -// next level, so it must convert that to the terminal ErrNotFound — otherwise -// the enricher would read "no error" as success and settle the candidate as -// enriched with zero tags. -func TestMusicBrainzFetchArtistTags_UntaggedArtistIsNotFound(t *testing.T) { - srv := mbEntityServer(``, `{"tags":[]}`) - defer srv.Close() - old := mbBaseURL - mbBaseURL = srv.URL - defer func() { mbBaseURL = old }() - - _, err := newMBProvider(true).FetchArtistTags(context.Background(), ArtistRef{MBID: "art-1"}) - if !errors.Is(err, ErrNotFound) { - t.Errorf("err = %v, want ErrNotFound", err) - } -} - -func TestLastfmFetchArtistTags_CallsArtistGetTopTags(t *testing.T) { - var gotMethod, gotArtist, gotMBID string - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotMethod = r.URL.Query().Get("method") - gotArtist = r.URL.Query().Get("artist") - gotMBID = r.URL.Query().Get("mbid") - _, _ = w.Write([]byte(`{"toptags":{"tag":[{"name":"post-punk","count":100},{"name":"moody","count":40}]}}`)) - })) - defer srv.Close() - old := lastfmBaseURL - lastfmBaseURL = srv.URL + "/" - defer func() { lastfmBaseURL = old }() - - p := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", MaxRetries: 1})} - _ = p.Configure(ProviderSettings{Enabled: true, APIKey: "k"}) - - tags, err := p.FetchArtistTags(context.Background(), - ArtistRef{MBID: "art-1", Name: "Some Band"}) - if err != nil { - t.Fatalf("fetch: %v", err) - } - if gotMethod != "artist.gettoptags" { - t.Errorf("method = %q, want artist.gettoptags", gotMethod) - } - if gotArtist != "Some Band" { - t.Errorf("artist = %q, want Some Band", gotArtist) - } - // MBID is sent as a disambiguating hint when we have one. - if gotMBID != "art-1" { - t.Errorf("mbid = %q, want art-1", gotMBID) - } - m := tagsByName(tags) - if m["post-punk"] != 1.0 { - t.Errorf("post-punk = %v, want 1.0", m["post-punk"]) - } - if m["moody"] != 0.4 { - t.Errorf("moody = %v, want 0.4", m["moody"]) - } -} - -func TestLastfmFetchArtistTags_GatedOff(t *testing.T) { - unkeyed := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", MaxRetries: 1})} - _ = unkeyed.Configure(ProviderSettings{Enabled: true}) - if _, err := unkeyed.FetchArtistTags(context.Background(), - ArtistRef{Name: "A"}); !errors.Is(err, ErrNotFound) { - t.Errorf("unkeyed: err = %v, want ErrNotFound", err) - } - - keyed := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", MaxRetries: 1})} - _ = keyed.Configure(ProviderSettings{Enabled: false, APIKey: "k"}) - if _, err := keyed.FetchArtistTags(context.Background(), - ArtistRef{Name: "A"}); !errors.Is(err, ErrNotFound) { - t.Errorf("disabled: err = %v, want ErrNotFound", err) - } - - // Name-based provider with no name → nothing to query. This is the case - // that matters in practice: a candidate whose name coalesced to '' still - // has an MBID, so MusicBrainz can serve it while Last.fm cannot. - enabled := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", MaxRetries: 1})} - _ = enabled.Configure(ProviderSettings{Enabled: true, APIKey: "k"}) - if _, err := enabled.FetchArtistTags(context.Background(), - ArtistRef{MBID: "art-1"}); !errors.Is(err, ErrNotFound) { - t.Errorf("no name: err = %v, want ErrNotFound", err) - } -} - -func TestLastfmFetchArtistTags_TransientErrorCodeRetries(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - _, _ = w.Write([]byte(`{"error":29}`)) // rate limited - })) - defer srv.Close() - old := lastfmBaseURL - lastfmBaseURL = srv.URL + "/" - defer func() { lastfmBaseURL = old }() - - p := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", MaxRetries: 1})} - _ = p.Configure(ProviderSettings{Enabled: true, APIKey: "k"}) - _, err := p.FetchArtistTags(context.Background(), ArtistRef{Name: "A"}) - // Must be ErrTransient, not ErrNotFound: the enricher settles a candidate - // to 'none' on ErrNotFound, which would permanently write off an artist we - // were merely throttled on. - if !errors.Is(err, ErrTransient) { - t.Errorf("err = %v, want ErrTransient", err) - } -} - -func TestLastfmFetchArtistTags_UnknownArtistIsNotFound(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - _, _ = w.Write([]byte(`{"error":6}`)) // "not found" — terminal - })) - defer srv.Close() - old := lastfmBaseURL - lastfmBaseURL = srv.URL + "/" - defer func() { lastfmBaseURL = old }() - - p := &lastfmProvider{client: newHTTPClient(httpClientOptions{Name: "lastfm", MaxRetries: 1})} - _ = p.Configure(ProviderSettings{Enabled: true, APIKey: "k"}) - if _, err := p.FetchArtistTags(context.Background(), - ArtistRef{Name: "Nobody"}); !errors.Is(err, ErrNotFound) { - t.Errorf("err = %v, want ErrNotFound", err) - } -}