Queue scrobbles offline and flush with WorkManager
When a submit fails for a transient reason (no connection, bad gateway, server error, rate limit) the scrobble is saved to a Room table and a network-constrained WorkManager job sends it later, in batches of 50, oldest first. Plays too old for the server are dropped, and a rejected session or unexpected error leaves the queue untouched. Safe to retry as the server dedupes on (user, played_at, artist, track). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ee34963799
commit
fa4eab47b3
15 files changed
+488
-12
No files matched your search
@@ -2,6 +2,7 @@ plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
alias(libs.plugins.kotlin.serialization)
|
||||
alias(libs.plugins.ksp)
|
||||
}
|
||||
|
||||
android {
|
||||
@@ -51,8 +52,13 @@ dependencies {
|
||||
implementation(libs.okhttp)
|
||||
implementation(libs.kotlinx.serialization.json)
|
||||
implementation(libs.kotlinx.coroutines.core)
|
||||
implementation(libs.androidx.room.runtime)
|
||||
implementation(libs.androidx.room.ktx)
|
||||
ksp(libs.androidx.room.compiler)
|
||||
implementation(libs.androidx.work.runtime.ktx)
|
||||
debugImplementation(libs.androidx.compose.ui.tooling)
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.androidx.work.testing)
|
||||
testImplementation(libs.okhttp.mockwebserver)
|
||||
testImplementation(libs.kotlinx.coroutines.test)
|
||||
androidTestImplementation(libs.androidx.espresso.core)
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
package dev.daubney.scrobbled
|
||||
|
||||
import android.app.Application
|
||||
import androidx.room.Room
|
||||
import dev.daubney.scrobbled.data.queue.AppDatabase
|
||||
import dev.daubney.scrobbled.data.queue.FlushScheduler
|
||||
import dev.daubney.scrobbled.data.queue.QueueFlusher
|
||||
import dev.daubney.scrobbled.data.queue.QueueStore
|
||||
import dev.daubney.scrobbled.data.queue.RoomQueueStore
|
||||
import dev.daubney.scrobbled.data.queue.WorkManagerFlushScheduler
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
import dev.daubney.scrobbled.data.auth.AuthRepository
|
||||
import dev.daubney.scrobbled.data.auth.DefaultAuthRepository
|
||||
import dev.daubney.scrobbled.data.auth.KeystoreCredentialStore
|
||||
@@ -15,6 +26,18 @@ import dev.daubney.scrobbled.data.search.TrackSearch
|
||||
class ScrobbledApplication : Application() {
|
||||
val auth: AuthRepository by lazy { DefaultAuthRepository(KeystoreCredentialStore(this)) }
|
||||
val history: HistoryRepository by lazy { DefaultHistoryRepository(auth) }
|
||||
val scrobbles: ScrobbleRepository by lazy { DefaultScrobbleRepository(auth) }
|
||||
private val database by lazy { Room.databaseBuilder(this, AppDatabase::class.java, "scrobbled.db").build() }
|
||||
val queue: QueueStore by lazy { RoomQueueStore(database.queueDao()) }
|
||||
private val scheduler: FlushScheduler by lazy { WorkManagerFlushScheduler(this) }
|
||||
val queueFlusher by lazy { QueueFlusher(queue, auth) }
|
||||
val scrobbles: ScrobbleRepository by lazy { DefaultScrobbleRepository(auth, queue, scheduler) }
|
||||
val trackSearch: TrackSearch by lazy { MusicBrainzSearch() }
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
// Anything left over from a previous run (app killed while offline) gets another go.
|
||||
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
|
||||
if (queue.count() > 0) scheduler.schedule()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,4 +20,7 @@ data class ScrobbleResult(val accepted: Int, val ignored: Int)
|
||||
class LastFmException(val code: Int, message: String) : Exception(message) {
|
||||
/** The session key was rejected; the user must re-authenticate. */
|
||||
val isInvalidSession get() = code == 9
|
||||
|
||||
/** Worth retrying later: no connection / bad gateway (-1), server hiccup (8) or rate limiting (29). */
|
||||
val isTransient get() = code == -1 || code == 8 || code == 29
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package dev.daubney.scrobbled.data.queue
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.BackoffPolicy
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.WorkerParameters
|
||||
import dev.daubney.scrobbled.ScrobbledApplication
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
fun interface FlushScheduler {
|
||||
/** Arranges for the queue to be sent as soon as the device is online. */
|
||||
fun schedule()
|
||||
}
|
||||
|
||||
class WorkManagerFlushScheduler(private val context: Context) : FlushScheduler {
|
||||
override fun schedule() {
|
||||
val request = OneTimeWorkRequestBuilder<QueueWorker>()
|
||||
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
|
||||
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
|
||||
.build()
|
||||
// REPLACE so a worker sitting in backoff is restarted when new work arrives.
|
||||
WorkManager.getInstance(context).enqueueUniqueWork(WORK_NAME, ExistingWorkPolicy.REPLACE, request)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val WORK_NAME = "flush-scrobble-queue"
|
||||
}
|
||||
}
|
||||
|
||||
class QueueWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
|
||||
override suspend fun doWork(): Result {
|
||||
val app = applicationContext as ScrobbledApplication
|
||||
return when (app.queueFlusher.flush()) {
|
||||
is FlushResult.Done, is FlushResult.Blocked -> Result.success()
|
||||
FlushResult.Retry -> Result.retry()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package dev.daubney.scrobbled.data.queue
|
||||
|
||||
import dev.daubney.scrobbled.data.api.LastFmClient
|
||||
import dev.daubney.scrobbled.data.api.LastFmException
|
||||
import dev.daubney.scrobbled.data.auth.AuthRepository
|
||||
import dev.daubney.scrobbled.data.scrobble.TrackDraft
|
||||
import java.time.Instant
|
||||
|
||||
sealed interface FlushResult {
|
||||
/** Queue is empty. [sent] were accepted; [dropped] were refused by the server or too old to ever be accepted. */
|
||||
data class Done(val sent: Int, val dropped: Int) : FlushResult
|
||||
|
||||
/** A temporary failure (offline, server busy): try again later. */
|
||||
data object Retry : FlushResult
|
||||
|
||||
/** Needs the user: signed out, session rejected, or an unexpected server error. Items are kept. */
|
||||
data class Blocked(val reason: String) : FlushResult
|
||||
}
|
||||
|
||||
/** Sends queued scrobbles in batches of up to 50, oldest first. Safe to re-run: the server dedupes retries. */
|
||||
class QueueFlusher(
|
||||
private val store: QueueStore,
|
||||
private val auth: AuthRepository,
|
||||
private val lastFmFor: (url: String, key: String, secret: String) -> LastFmClient =
|
||||
{ url, key, secret -> LastFmClient(url, key, secret) },
|
||||
private val now: () -> Instant = Instant::now,
|
||||
) {
|
||||
suspend fun flush(): FlushResult {
|
||||
var sent = 0
|
||||
var dropped = 0
|
||||
while (true) {
|
||||
val batch = store.pending(BATCH)
|
||||
if (batch.isEmpty()) return FlushResult.Done(sent, dropped)
|
||||
|
||||
// The server refuses plays older than 14 days, so those can never succeed.
|
||||
val cutoff = now().minus(TrackDraft.MAX_AGE)
|
||||
val (expired, sendable) = batch.partition { it.draft.playedAt.isBefore(cutoff) }
|
||||
if (expired.isNotEmpty()) {
|
||||
store.remove(expired.map { it.id })
|
||||
dropped += expired.size
|
||||
}
|
||||
if (sendable.isEmpty()) continue
|
||||
|
||||
val creds = auth.current() ?: return FlushResult.Blocked("Not signed in")
|
||||
val result = try {
|
||||
lastFmFor(creds.serverUrl, creds.apiKey, creds.apiSecret)
|
||||
.scrobble(creds.sessionKey, sendable.map { it.draft.toScrobbleTrack() })
|
||||
} catch (e: LastFmException) {
|
||||
return when {
|
||||
e.isInvalidSession -> FlushResult.Blocked("Session expired")
|
||||
e.isTransient -> FlushResult.Retry
|
||||
else -> FlushResult.Blocked(e.message.orEmpty())
|
||||
}
|
||||
}
|
||||
store.remove(sendable.map { it.id })
|
||||
sent += result.accepted
|
||||
dropped += result.ignored
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val BATCH = 50
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package dev.daubney.scrobbled.data.queue
|
||||
|
||||
import dev.daubney.scrobbled.data.scrobble.TrackDraft
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
data class QueuedItem(val id: Long, val draft: TrackDraft)
|
||||
|
||||
/** Scrobbles that couldn't be sent yet, oldest play first. */
|
||||
interface QueueStore {
|
||||
suspend fun add(draft: TrackDraft)
|
||||
suspend fun pending(limit: Int): List<QueuedItem>
|
||||
suspend fun remove(ids: List<Long>)
|
||||
suspend fun count(): Int
|
||||
fun observeCount(): Flow<Int>
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package dev.daubney.scrobbled.data.queue
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Database
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Insert
|
||||
import androidx.room.PrimaryKey
|
||||
import androidx.room.Query
|
||||
import androidx.room.RoomDatabase
|
||||
import dev.daubney.scrobbled.data.scrobble.TrackDraft
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import java.time.Instant
|
||||
|
||||
@Entity(tableName = "queued_scrobbles")
|
||||
data class QueuedScrobbleEntity(
|
||||
@PrimaryKey(autoGenerate = true) val id: Long = 0,
|
||||
val artist: String,
|
||||
val track: String,
|
||||
val album: String,
|
||||
val albumArtist: String,
|
||||
val durationSeconds: Int?,
|
||||
val mbid: String,
|
||||
val playedAt: Long,
|
||||
)
|
||||
|
||||
@Dao
|
||||
interface QueueDao {
|
||||
@Insert
|
||||
suspend fun insert(entity: QueuedScrobbleEntity)
|
||||
|
||||
@Query("SELECT * FROM queued_scrobbles ORDER BY playedAt ASC, id ASC LIMIT :limit")
|
||||
suspend fun pending(limit: Int): List<QueuedScrobbleEntity>
|
||||
|
||||
@Query("DELETE FROM queued_scrobbles WHERE id IN (:ids)")
|
||||
suspend fun delete(ids: List<Long>)
|
||||
|
||||
@Query("SELECT COUNT(*) FROM queued_scrobbles")
|
||||
suspend fun count(): Int
|
||||
|
||||
@Query("SELECT COUNT(*) FROM queued_scrobbles")
|
||||
fun observeCount(): Flow<Int>
|
||||
}
|
||||
|
||||
@Database(entities = [QueuedScrobbleEntity::class], version = 1, exportSchema = false)
|
||||
abstract class AppDatabase : RoomDatabase() {
|
||||
abstract fun queueDao(): QueueDao
|
||||
}
|
||||
|
||||
class RoomQueueStore(private val dao: QueueDao) : QueueStore {
|
||||
override suspend fun add(draft: TrackDraft) = dao.insert(
|
||||
QueuedScrobbleEntity(
|
||||
artist = draft.artist, track = draft.track, album = draft.album, albumArtist = draft.albumArtist,
|
||||
durationSeconds = draft.durationSeconds, mbid = draft.mbid, playedAt = draft.playedAt.epochSecond,
|
||||
),
|
||||
)
|
||||
|
||||
override suspend fun pending(limit: Int) = dao.pending(limit).map {
|
||||
QueuedItem(
|
||||
it.id,
|
||||
TrackDraft(
|
||||
artist = it.artist, track = it.track, album = it.album, albumArtist = it.albumArtist,
|
||||
durationSeconds = it.durationSeconds, mbid = it.mbid, playedAt = Instant.ofEpochSecond(it.playedAt),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun remove(ids: List<Long>) = dao.delete(ids)
|
||||
override suspend fun count() = dao.count()
|
||||
override fun observeCount() = dao.observeCount()
|
||||
}
|
||||
@@ -4,28 +4,51 @@ import dev.daubney.scrobbled.data.api.LastFmClient
|
||||
import dev.daubney.scrobbled.data.api.LastFmException
|
||||
import dev.daubney.scrobbled.data.auth.AuthRepository
|
||||
import dev.daubney.scrobbled.data.history.SessionExpiredException
|
||||
import dev.daubney.scrobbled.data.queue.FlushScheduler
|
||||
import dev.daubney.scrobbled.data.queue.QueueStore
|
||||
|
||||
enum class SubmitResult {
|
||||
/** The server accepted it. */
|
||||
Sent,
|
||||
|
||||
/** Couldn't reach the server; saved and will be sent automatically when back online. */
|
||||
Queued,
|
||||
}
|
||||
|
||||
interface ScrobbleRepository {
|
||||
/** Submits one scrobble; throws if it can't be accepted. */
|
||||
suspend fun submit(draft: TrackDraft)
|
||||
/** Submits one scrobble. Throws if it can't be accepted and isn't worth retrying. */
|
||||
suspend fun submit(draft: TrackDraft): SubmitResult
|
||||
}
|
||||
|
||||
class DefaultScrobbleRepository(
|
||||
private val auth: AuthRepository,
|
||||
private val queue: QueueStore,
|
||||
private val scheduler: FlushScheduler,
|
||||
private val lastFmFor: (url: String, key: String, secret: String) -> LastFmClient =
|
||||
{ url, key, secret -> LastFmClient(url, key, secret) },
|
||||
) : ScrobbleRepository {
|
||||
|
||||
override suspend fun submit(draft: TrackDraft) {
|
||||
override suspend fun submit(draft: TrackDraft): SubmitResult {
|
||||
draft.validate()?.let { throw IllegalArgumentException(it) }
|
||||
val creds = auth.current() ?: throw SessionExpiredException()
|
||||
val result = try {
|
||||
lastFmFor(creds.serverUrl, creds.apiKey, creds.apiSecret)
|
||||
.scrobble(creds.sessionKey, listOf(draft.toScrobbleTrack()))
|
||||
} catch (e: LastFmException) {
|
||||
throw if (e.isInvalidSession) SessionExpiredException() else e
|
||||
when {
|
||||
e.isInvalidSession -> throw SessionExpiredException()
|
||||
e.isTransient -> {
|
||||
queue.add(draft)
|
||||
scheduler.schedule()
|
||||
return SubmitResult.Queued
|
||||
}
|
||||
else -> throw e
|
||||
}
|
||||
}
|
||||
// The server reports bad or stale tracks as "ignored" rather than as an error.
|
||||
if (result.accepted < 1) throw IllegalStateException("The server didn't accept this scrobble")
|
||||
// We're online, so this is a good moment to send anything saved earlier.
|
||||
if (queue.count() > 0) scheduler.schedule()
|
||||
return SubmitResult.Sent
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package dev.daubney.scrobbled.ui.add
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import dev.daubney.scrobbled.data.scrobble.ScrobbleRepository
|
||||
import dev.daubney.scrobbled.data.scrobble.SubmitResult
|
||||
import dev.daubney.scrobbled.data.scrobble.TrackDraft
|
||||
import dev.daubney.scrobbled.data.search.SearchException
|
||||
import dev.daubney.scrobbled.data.search.TrackResult
|
||||
@@ -106,12 +107,16 @@ class AddViewModel(
|
||||
_state.update { it.copy(submitting = true, error = null, message = null) }
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
scrobbles.submit(draft)
|
||||
val outcome = scrobbles.submit(draft)
|
||||
// Keep the time choice and search (adding several tracks in a row is common), clear the form.
|
||||
_state.update {
|
||||
it.copy(
|
||||
artist = "", track = "", album = "", mbid = "", durationSeconds = null,
|
||||
submitting = false, message = "Scrobbled ${draft.track.trim()}",
|
||||
submitting = false,
|
||||
message = when (outcome) {
|
||||
SubmitResult.Sent -> "Scrobbled ${draft.track.trim()}"
|
||||
SubmitResult.Queued -> "Saved ${draft.track.trim()}. It will be sent when you're back online."
|
||||
},
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package dev.daubney.scrobbled.data.queue
|
||||
|
||||
import dev.daubney.scrobbled.data.scrobble.TrackDraft
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
class InMemoryQueue : QueueStore {
|
||||
private val items = MutableStateFlow<List<QueuedItem>>(emptyList())
|
||||
private var nextId = 1L
|
||||
val all get() = items.value
|
||||
|
||||
override suspend fun add(draft: TrackDraft) { items.value = items.value + QueuedItem(nextId++, draft) }
|
||||
override suspend fun pending(limit: Int) =
|
||||
items.value.sortedWith(compareBy({ it.draft.playedAt }, { it.id })).take(limit)
|
||||
override suspend fun remove(ids: List<Long>) { items.value = items.value.filter { it.id !in ids } }
|
||||
override suspend fun count() = items.value.size
|
||||
override fun observeCount() = items.map { it.size }
|
||||
}
|
||||
|
||||
class RecordingScheduler : FlushScheduler {
|
||||
var calls = 0
|
||||
override fun schedule() { calls++ }
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package dev.daubney.scrobbled.data.queue
|
||||
|
||||
import dev.daubney.scrobbled.data.auth.AuthRepository
|
||||
import dev.daubney.scrobbled.data.auth.Credentials
|
||||
import dev.daubney.scrobbled.data.scrobble.TrackDraft
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import java.net.URLDecoder
|
||||
import java.time.Duration
|
||||
import java.time.Instant
|
||||
|
||||
class QueueFlusherTest {
|
||||
private val now = Instant.parse("2026-10-12T12:00:00Z")
|
||||
private lateinit var server: MockWebServer
|
||||
private val store = InMemoryQueue()
|
||||
private var creds: Credentials? = null
|
||||
private val auth = object : AuthRepository {
|
||||
override fun current() = creds
|
||||
override suspend fun connect(serverUrl: String, username: String, password: String) = error("unused")
|
||||
override fun disconnect() {}
|
||||
}
|
||||
private lateinit var flusher: QueueFlusher
|
||||
|
||||
@Before fun setUp() {
|
||||
server = MockWebServer().also { it.start() }
|
||||
creds = Credentials(server.url("/").toString().trimEnd('/'), "a", "t", "key", "secret", "sess")
|
||||
flusher = QueueFlusher(store, auth, now = { now })
|
||||
}
|
||||
@After fun tearDown() = server.shutdown()
|
||||
|
||||
private suspend fun enqueue(n: Int, ageMinutes: Long = 10) = repeat(n) {
|
||||
store.add(TrackDraft(artist = "A", track = "T$it", playedAt = now.minus(Duration.ofMinutes(ageMinutes)).minusSeconds(it.toLong())))
|
||||
}
|
||||
private fun ok(accepted: Int, ignored: Int = 0) = MockResponse().setBody(
|
||||
"""{"scrobbles":{"scrobble":[],"@attr":{"accepted":"$accepted","ignored":"$ignored"}}}""")
|
||||
|
||||
@Test
|
||||
fun emptyQueueMakesNoRequest() = runTest {
|
||||
assertEquals(FlushResult.Done(0, 0), flusher.flush())
|
||||
assertEquals(0, server.requestCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sendsOldestFirstAndEmptiesTheQueue() = runTest {
|
||||
enqueue(3)
|
||||
server.enqueue(ok(3))
|
||||
assertEquals(FlushResult.Done(3, 0), flusher.flush())
|
||||
assertEquals(0, store.count())
|
||||
val body = URLDecoder.decode(server.takeRequest().body.readUtf8(), "UTF-8")
|
||||
// T2 was played earliest, so it must be index 0
|
||||
assertTrue(body.contains("track[0]=T2"))
|
||||
assertTrue(body.contains("track[2]=T0"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun largeQueueIsSentInBatchesOf50() = runTest {
|
||||
enqueue(120)
|
||||
server.enqueue(ok(50)); server.enqueue(ok(50)); server.enqueue(ok(20))
|
||||
assertEquals(FlushResult.Done(120, 0), flusher.flush())
|
||||
assertEquals(3, server.requestCount)
|
||||
assertEquals(0, store.count())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ignoredScrobblesAreDroppedNotRetriedForever() = runTest {
|
||||
enqueue(2)
|
||||
server.enqueue(ok(1, 1))
|
||||
assertEquals(FlushResult.Done(1, 1), flusher.flush())
|
||||
assertEquals(0, store.count())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun offlineKeepsItemsAndAsksForRetry() = runTest {
|
||||
enqueue(2)
|
||||
server.enqueue(MockResponse().setResponseCode(502).setBody("<html>bad gateway</html>"))
|
||||
assertEquals(FlushResult.Retry, flusher.flush())
|
||||
assertEquals(2, store.count())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun serverBusyKeepsItemsAndAsksForRetry() = runTest {
|
||||
enqueue(1)
|
||||
server.enqueue(MockResponse().setResponseCode(429).setBody("""{"error":29,"message":"Rate limit exceeded"}"""))
|
||||
assertEquals(FlushResult.Retry, flusher.flush())
|
||||
assertEquals(1, store.count())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectedSessionBlocksAndKeepsItems() = runTest {
|
||||
enqueue(2)
|
||||
server.enqueue(MockResponse().setResponseCode(403).setBody("""{"error":9,"message":"Invalid session key"}"""))
|
||||
assertEquals(FlushResult.Blocked("Session expired"), flusher.flush())
|
||||
assertEquals(2, store.count())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unexpectedServerErrorBlocksAndKeepsItems() = runTest {
|
||||
enqueue(1)
|
||||
server.enqueue(MockResponse().setResponseCode(400).setBody("""{"error":6,"message":"Invalid parameters"}"""))
|
||||
assertEquals(FlushResult.Blocked("Invalid parameters"), flusher.flush())
|
||||
assertEquals(1, store.count())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun signedOutBlocksWithoutRequest() = runTest {
|
||||
enqueue(1)
|
||||
creds = null
|
||||
assertEquals(FlushResult.Blocked("Not signed in"), flusher.flush())
|
||||
assertEquals(0, server.requestCount)
|
||||
assertEquals(1, store.count())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun playsOlderThanFourteenDaysAreDroppedWithoutSending() = runTest {
|
||||
enqueue(1, ageMinutes = 15 * 24 * 60)
|
||||
assertEquals(FlushResult.Done(0, 1), flusher.flush())
|
||||
assertEquals(0, server.requestCount)
|
||||
assertEquals(0, store.count())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mixedBatchDropsExpiredAndSendsTheRest() = runTest {
|
||||
enqueue(1, ageMinutes = 15 * 24 * 60)
|
||||
enqueue(2)
|
||||
server.enqueue(ok(2))
|
||||
assertEquals(FlushResult.Done(2, 1), flusher.flush())
|
||||
assertEquals(0, store.count())
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import dev.daubney.scrobbled.data.api.LastFmException
|
||||
import dev.daubney.scrobbled.data.auth.AuthRepository
|
||||
import dev.daubney.scrobbled.data.auth.Credentials
|
||||
import dev.daubney.scrobbled.data.history.SessionExpiredException
|
||||
import dev.daubney.scrobbled.data.queue.InMemoryQueue
|
||||
import dev.daubney.scrobbled.data.queue.RecordingScheduler
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
@@ -25,13 +27,15 @@ class ScrobbleRepositoryTest {
|
||||
override suspend fun connect(serverUrl: String, username: String, password: String) = error("unused")
|
||||
override fun disconnect() {}
|
||||
}
|
||||
private val queue = InMemoryQueue()
|
||||
private val scheduler = RecordingScheduler()
|
||||
private lateinit var repo: DefaultScrobbleRepository
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
server = MockWebServer().also { it.start() }
|
||||
creds = Credentials(server.url("/").toString().trimEnd('/'), "alice", "tok", "key", "secret", "sess")
|
||||
repo = DefaultScrobbleRepository(auth) { url, key, secret -> LastFmClient(url, key, secret) }
|
||||
repo = DefaultScrobbleRepository(auth, queue, scheduler) { url, key, secret -> LastFmClient(url, key, secret) }
|
||||
}
|
||||
|
||||
@After fun tearDown() = server.shutdown()
|
||||
@@ -43,7 +47,7 @@ class ScrobbleRepositoryTest {
|
||||
@Test
|
||||
fun submitSendsSessionKeyAndFields() = runTest {
|
||||
server.enqueue(ok(1, 0))
|
||||
repo.submit(draft)
|
||||
assertEquals(SubmitResult.Sent, repo.submit(draft))
|
||||
val body = URLDecoder.decode(server.takeRequest().body.readUtf8(), "UTF-8")
|
||||
assertTrue(body.contains("sk=sess"))
|
||||
assertTrue(body.contains("artist[0]=A"))
|
||||
@@ -67,8 +71,9 @@ class ScrobbleRepositoryTest {
|
||||
|
||||
@Test
|
||||
fun otherServerErrorsPropagate() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(500).setBody("""{"error":8,"message":"Operation failed"}"""))
|
||||
try { repo.submit(draft); fail() } catch (e: LastFmException) { assertEquals(8, e.code) }
|
||||
server.enqueue(MockResponse().setResponseCode(400).setBody("""{"error":6,"message":"Invalid parameters"}"""))
|
||||
try { repo.submit(draft); fail() } catch (e: LastFmException) { assertEquals(6, e.code) }
|
||||
assertEquals(0, queue.all.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -82,4 +87,44 @@ class ScrobbleRepositoryTest {
|
||||
creds = null
|
||||
try { repo.submit(draft); fail() } catch (e: SessionExpiredException) { }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun networkFailureQueuesAndSchedulesAFlush() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(502).setBody("<html>bad gateway</html>"))
|
||||
assertEquals(SubmitResult.Queued, repo.submit(draft))
|
||||
assertEquals(1, queue.all.size)
|
||||
assertEquals("T", queue.all.single().draft.track)
|
||||
assertEquals(1, scheduler.calls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun serverErrorAndRateLimitAlsoQueue() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(500).setBody("""{"error":8,"message":"Operation failed"}"""))
|
||||
server.enqueue(MockResponse().setResponseCode(429).setBody("""{"error":29,"message":"Rate limit exceeded"}"""))
|
||||
assertEquals(SubmitResult.Queued, repo.submit(draft))
|
||||
assertEquals(SubmitResult.Queued, repo.submit(draft))
|
||||
assertEquals(2, queue.all.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectedSessionIsNotQueued() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(403).setBody("""{"error":9,"message":"Invalid session key"}"""))
|
||||
try { repo.submit(draft); fail() } catch (e: SessionExpiredException) { }
|
||||
assertEquals(0, queue.all.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun successWithBacklogSchedulesAFlush() = runTest {
|
||||
queue.add(draft)
|
||||
server.enqueue(ok(1, 0))
|
||||
repo.submit(draft)
|
||||
assertEquals(1, scheduler.calls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun successWithEmptyQueueDoesNotSchedule() = runTest {
|
||||
server.enqueue(ok(1, 0))
|
||||
repo.submit(draft)
|
||||
assertEquals(0, scheduler.calls)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package dev.daubney.scrobbled.ui.add
|
||||
|
||||
import dev.daubney.scrobbled.data.scrobble.ScrobbleRepository
|
||||
import dev.daubney.scrobbled.data.scrobble.SubmitResult
|
||||
import dev.daubney.scrobbled.data.scrobble.TrackDraft
|
||||
import dev.daubney.scrobbled.data.search.SearchException
|
||||
import dev.daubney.scrobbled.data.search.TrackResult
|
||||
@@ -22,9 +23,11 @@ import java.time.Instant
|
||||
private class FakeScrobbles : ScrobbleRepository {
|
||||
val submitted = mutableListOf<TrackDraft>()
|
||||
var failure: Exception? = null
|
||||
override suspend fun submit(draft: TrackDraft) {
|
||||
var result = SubmitResult.Sent
|
||||
override suspend fun submit(draft: TrackDraft): SubmitResult {
|
||||
failure?.let { throw it }
|
||||
submitted += draft
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,4 +184,12 @@ class AddViewModelTest {
|
||||
assertEquals(1, vm.state.value.results.size)
|
||||
assertEquals("", vm.state.value.mbid)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun queuedSubmitSaysItWillBeSentLater() {
|
||||
repo.result = SubmitResult.Queued
|
||||
fill(); vm.submit()
|
||||
assertEquals("Saved Reckoner. It will be sent when you're back online.", vm.state.value.message)
|
||||
assertEquals("", vm.state.value.track) // form clears: the scrobble is safely stored
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user