From 9bf831e20ed2def2a92cad550eeb0c69a18c7d26 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Fri, 27 Nov 2026 10:23:38 -0500 Subject: [PATCH] refactor(android): one rule for which failed writes wait in the offline queue (DRY D1) Six repositories decided for themselves which failed writes to queue: playlists queued only on no answer, notifications split 4xx from 5xx, and likes and hidden tracks queued everything, a refusal included, which the replayer then sent again only to drop it. They all go through cache/mutations/sendOrQueue now: no answer, a 5xx, 408 or 429 queue the write; any other 4xx is a refusal and is not queued (playlists still throw it so the screen can say why; the others log it). Cancellation passes through. isRetryableStatus is the one test of a retryable status, and the replayer's isPermanent is its complement. WriteOutcome moves to cache/mutations and gains Refused. Co-Authored-By: Claude Opus 5.5 --- .../cache/mutations/MutationReplayer.kt | 13 +---- .../minstrel/cache/mutations/SendOrQueue.kt | 58 +++++++++++++++++++ .../minstrel/likes/data/LikesRepository.kt | 25 ++++---- .../data/NotificationSettingsRepository.kt | 21 ++++--- .../data/NotificationsRepository.kt | 49 ++++++---------- .../playlists/data/PlaylistsRepository.kt | 22 +------ .../playlists/ui/PlaylistDetailScreen.kt | 2 +- .../playlists/ui/PlaylistsListScreen.kt | 2 +- .../quarantine/data/QuarantineRepository.kt | 43 ++++++++------ .../settings/data/NormalizationRepository.kt | 21 ++++--- .../cache/mutations/SendOrQueueTest.kt | 54 +++++++++++++++++ 11 files changed, 194 insertions(+), 116 deletions(-) create mode 100644 android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/SendOrQueue.kt create mode 100644 android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SendOrQueueTest.kt 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 dc345c09..f0541450 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 @@ -181,10 +181,8 @@ class MutationReplayer @Inject constructor( Outcome.RETRY } - /** 4xx are permanent except the two "retry me" statuses. */ - private fun isPermanent(code: Int): Boolean = - code in HTTP_CLIENT_ERR_MIN..HTTP_CLIENT_ERR_MAX && - code != HTTP_TIMEOUT && code != HTTP_TOO_MANY + /** A refusal that a replay would only get again ([isRetryableStatus]'s complement). */ + private fun isPermanent(code: Int): Boolean = !isRetryableStatus(code) /** * Returns the outcome of replaying one row. SENT on a 2xx; DROP for an @@ -362,13 +360,6 @@ class MutationReplayer @Inject constructor( ) return Outcome.SENT } - - private companion object { - const val HTTP_CLIENT_ERR_MIN = 400 - const val HTTP_CLIENT_ERR_MAX = 499 - const val HTTP_TIMEOUT = 408 - const val HTTP_TOO_MANY = 429 - } } /** diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/SendOrQueue.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/SendOrQueue.kt new file mode 100644 index 00000000..a49863d6 --- /dev/null +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/SendOrQueue.kt @@ -0,0 +1,58 @@ +package com.fabledsword.minstrel.cache.mutations + +import kotlinx.coroutines.CancellationException +import retrofit2.HttpException + +/** Whether a write reached the server, waits in the offline queue, or was refused. */ +enum class WriteOutcome { Synced, Queued, Refused } + +private const val HTTP_CLIENT_ERR_MIN = 400 +private const val HTTP_CLIENT_ERR_MAX = 499 +private const val HTTP_TIMEOUT = 408 +private const val HTTP_TOO_MANY = 429 + +/** + * Whether a server's HTTP error is worth trying again later: a 5xx (the + * server's trouble), 408 (timed out) or 429 (too many requests). Any other + * 4xx is the server saying no, and asking again gets the same answer. + * The replayer and [sendOrQueue] both decide by this. + */ +fun isRetryableStatus(code: Int): Boolean = + code !in HTTP_CLIENT_ERR_MIN..HTTP_CLIENT_ERR_MAX || code == HTTP_TIMEOUT || code == HTTP_TOO_MANY + +/** + * Sends a write now, or queues it for the replayer when the server can't + * take it yet. The one rule every offline-first repository write follows: + * + * - The server took it: [WriteOutcome.Synced]. + * - No answer (offline, a dropped connection), or an error worth retrying + * ([isRetryableStatus]): [queue] runs and the result is Queued. + * - The server refused it (any other 4xx): nothing is queued, since a + * replay would be refused too. [onRefused] decides what the caller sees; + * by default the refusal is thrown, so the caller can say why. + * + * Cancellation passes through. + */ +suspend fun sendOrQueue( + send: suspend () -> Unit, + queue: suspend () -> Unit, + onRefused: (HttpException) -> WriteOutcome = { throw it }, +): WriteOutcome = + try { + send() + WriteOutcome.Synced + } catch (e: CancellationException) { + throw e + } catch (e: HttpException) { + if (isRetryableStatus(e.code())) { + queue() + WriteOutcome.Queued + } else { + onRefused(e) + } + } catch ( + @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, + ) { + queue() + WriteOutcome.Queued + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/likes/data/LikesRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/likes/data/LikesRepository.kt index 81e4240f..93a4e36e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/likes/data/LikesRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/likes/data/LikesRepository.kt @@ -1,5 +1,6 @@ package com.fabledsword.minstrel.likes.data +import com.fabledsword.minstrel.cache.mutations.WriteOutcome import com.fabledsword.minstrel.cache.mutations.likeToggleKey import com.fabledsword.minstrel.api.endpoints.LikesApi import com.fabledsword.minstrel.auth.AuthController @@ -9,6 +10,7 @@ import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao import com.fabledsword.minstrel.cache.db.entities.CachedLikeEntity import com.fabledsword.minstrel.cache.mutations.MutationQueue +import com.fabledsword.minstrel.cache.mutations.sendOrQueue import com.fabledsword.minstrel.di.ApplicationScope import com.fabledsword.minstrel.library.data.toDomain import com.fabledsword.minstrel.models.AlbumRef @@ -29,6 +31,7 @@ import retrofit2.create import javax.inject.Inject import javax.inject.Singleton import kotlin.time.Duration.Companion.milliseconds +import timber.log.Timber /** * Cache-first reads + offline-first writes for likes. @@ -182,18 +185,16 @@ class LikesRepository @Inject constructor( } // 2. Best-effort REST call; 3. enqueue on failure. val kindPath = serverPathFor(entityType) - return try { - if (desiredState) api.like(kindPath, entityId) else api.unlike(kindPath, entityId) - true - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Intentional swallow: the queue replays this later; surfacing - // the network error here would force callers (UI) to handle it - // even though it's already been buffered. - mutationQueue.enqueueLikeToggle(entityType, entityId, desiredState) - false - } + // A refusal isn't surfaced: the heart buttons don't wait on this call, + // and the next likes refresh puts the server's answer back on screen. + return sendOrQueue( + send = { if (desiredState) api.like(kindPath, entityId) else api.unlike(kindPath, entityId) }, + queue = { mutationQueue.enqueueLikeToggle(entityType, entityId, desiredState) }, + onRefused = { e -> + Timber.i(e, "likes: %s %s refused (%d)", entityType, entityId, e.code()) + WriteOutcome.Refused + }, + ) == WriteOutcome.Synced } /** diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepository.kt index 3aa3bd3b..dfac124c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepository.kt @@ -9,8 +9,9 @@ import com.fabledsword.minstrel.cache.db.entities.CachedNotificationSettingsEnti import com.fabledsword.minstrel.cache.mutations.MutationKind import com.fabledsword.minstrel.cache.mutations.MutationQueue import com.fabledsword.minstrel.cache.mutations.NotificationSettingPayload +import com.fabledsword.minstrel.cache.mutations.WriteOutcome import com.fabledsword.minstrel.cache.mutations.notificationSettingChange -import kotlinx.coroutines.CancellationException +import com.fabledsword.minstrel.cache.mutations.sendOrQueue import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.serialization.json.Json @@ -61,16 +62,14 @@ class NotificationSettingsRepository @Inject constructor( return } val change = notificationSettingChange(payload) ?: return - try { - save(api.putSettings(PutNotificationSettingsBody(listOf(change)))) - } catch (e: CancellationException) { - throw e - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - Timber.i(e, "notification settings: PUT failed; queued") - mutationQueue.enqueueNotificationSettingSet(payload) - } + sendOrQueue( + send = { save(api.putSettings(PutNotificationSettingsBody(listOf(change)))) }, + queue = { mutationQueue.enqueueNotificationSettingSet(payload) }, + onRefused = { e -> + Timber.i(e, "notification settings: PUT refused (%d)", e.code()) + WriteOutcome.Refused + }, + ) } private suspend fun current(): NotificationSettingsWire? = dao.getSettings()?.let(::decode) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationsRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationsRepository.kt index f6910934..f8e76e8b 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationsRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationsRepository.kt @@ -6,7 +6,8 @@ import com.fabledsword.minstrel.api.endpoints.ReadAllBody import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao import com.fabledsword.minstrel.cache.db.entities.CachedNotificationEntity import com.fabledsword.minstrel.cache.mutations.MutationQueue -import kotlinx.coroutines.CancellationException +import com.fabledsword.minstrel.cache.mutations.WriteOutcome +import com.fabledsword.minstrel.cache.mutations.sendOrQueue import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.datetime.Clock @@ -52,24 +53,12 @@ class NotificationsRepository @Inject constructor( suspend fun markRead(id: String) { dao.markRead(id, Clock.System.now()) - try { - api.markRead(id) - } catch (e: CancellationException) { - throw e - } catch (e: HttpException) { - // A 4xx (404: trimmed or gone server-side) leaves nothing to mark; - // a 5xx is the server's trouble, so the read waits in the queue. - if (e.code() >= HTTP_SERVER_ERROR) { - mutationQueue.enqueueNotificationRead(id) - } else { - Timber.i(e, "notifications: mark read refused (%d)", e.code()) - } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - Timber.i(e, "notifications: mark read failed; queued") - mutationQueue.enqueueNotificationRead(id) - } + // A refusal (404: trimmed or gone server-side) leaves nothing to mark. + sendOrQueue( + send = { api.markRead(id) }, + queue = { mutationQueue.enqueueNotificationRead(id) }, + onRefused = { e -> refused("mark read", e) }, + ) } /** @@ -80,16 +69,16 @@ class NotificationsRepository @Inject constructor( suspend fun markAllRead() { val upTo = readAllCutoff(dao.getAll().map { it.createdAt })?.toString() dao.markAllRead(Clock.System.now()) - try { - api.readAll(ReadAllBody(upTo = upTo)) - } catch (e: CancellationException) { - throw e - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - Timber.i(e, "notifications: mark all read failed; queued") - mutationQueue.enqueueNotificationsReadAll(upTo) - } + sendOrQueue( + send = { api.readAll(ReadAllBody(upTo = upTo)) }, + queue = { mutationQueue.enqueueNotificationsReadAll(upTo) }, + onRefused = { e -> refused("mark all read", e) }, + ) + } + + private fun refused(what: String, e: HttpException): WriteOutcome { + Timber.i(e, "notifications: %s refused (%d)", what, e.code()) + return WriteOutcome.Refused } /** The page the device holds, newest first. */ @@ -103,8 +92,6 @@ class NotificationsRepository @Inject constructor( companion object { /** The newest page the device keeps; older notices stay on the server. */ const val PAGE_SIZE = 50 - - private const val HTTP_SERVER_ERROR = 500 } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt index c0a75d2f..3312f442 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt @@ -6,6 +6,8 @@ import com.fabledsword.minstrel.api.endpoints.PlaylistsApi import com.fabledsword.minstrel.api.endpoints.ReorderTracksRequest import com.fabledsword.minstrel.api.endpoints.UpdatePlaylistRequest import com.fabledsword.minstrel.auth.AuthController +import com.fabledsword.minstrel.cache.mutations.WriteOutcome +import com.fabledsword.minstrel.cache.mutations.sendOrQueue import retrofit2.HttpException import java.net.HttpURLConnection import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao @@ -33,7 +35,6 @@ import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import retrofit2.Retrofit import retrofit2.create -import java.io.IOException import java.util.UUID import javax.inject.Inject import javax.inject.Singleton @@ -273,27 +274,8 @@ class PlaylistsRepository @Inject constructor( queue = { mutationQueue.enqueuePlaylistReorder(PlaylistReorderPayload(playlistId, trackIds)) }, ) } - - /** - * Sends a write, or queues it when the server can't be reached. An - * HTTP error is not queued: the server answered, and a replay would get - * the same answer. - */ - private suspend fun sendOrQueue(send: suspend () -> Unit, queue: suspend () -> Unit): WriteOutcome = - try { - send() - WriteOutcome.Synced - } catch ( - @Suppress("SwallowedException") _: IOException, - ) { - queue() - WriteOutcome.Queued - } } -/** Whether a write reached the server or waits in the offline queue. */ -enum class WriteOutcome { Synced, Queued } - /** * Snapshot of a playlist + its per-track display fields, as returned * by `PlaylistsRepository.refreshDetail`. UI uses this directly for diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistDetailScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistDetailScreen.kt index ce7131cd..e9ba356c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistDetailScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistDetailScreen.kt @@ -61,6 +61,7 @@ import com.composables.icons.lucide.RefreshCw import com.composables.icons.lucide.Shuffle import com.fabledsword.minstrel.api.ErrorCopy import com.fabledsword.minstrel.auth.AuthController +import com.fabledsword.minstrel.cache.mutations.WriteOutcome import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.events.EventsStream @@ -76,7 +77,6 @@ import com.fabledsword.minstrel.player.PlayerController import com.fabledsword.minstrel.likes.data.LikesRepository import com.fabledsword.minstrel.playlists.data.PlaylistDetailRef import com.fabledsword.minstrel.playlists.data.PlaylistsRepository -import com.fabledsword.minstrel.playlists.data.WriteOutcome import com.fabledsword.minstrel.playlists.data.entryKeys import com.fabledsword.minstrel.playlists.data.toPlayableTrackRefs import com.fabledsword.minstrel.playlists.data.trackOrder diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistsListScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistsListScreen.kt index 107dc74f..41b0bfbf 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistsListScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistsListScreen.kt @@ -35,6 +35,7 @@ import androidx.navigation.NavHostController import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.Plus import com.fabledsword.minstrel.api.ErrorCopy +import com.fabledsword.minstrel.cache.mutations.WriteOutcome import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.ServerHealth import com.fabledsword.minstrel.connectivity.recoveries @@ -44,7 +45,6 @@ import com.fabledsword.minstrel.nav.PlaylistDetail import com.fabledsword.minstrel.nav.Playlists import com.fabledsword.minstrel.player.PlayerController import com.fabledsword.minstrel.playlists.data.PlaylistsRepository -import com.fabledsword.minstrel.playlists.data.WriteOutcome import com.fabledsword.minstrel.playlists.data.playPlaylistShuffled import com.fabledsword.minstrel.shared.UiState import com.fabledsword.minstrel.shared.asCacheFirstStateFlow diff --git a/android/app/src/main/java/com/fabledsword/minstrel/quarantine/data/QuarantineRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/quarantine/data/QuarantineRepository.kt index 7f456f47..2a9a706e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/quarantine/data/QuarantineRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/quarantine/data/QuarantineRepository.kt @@ -5,6 +5,8 @@ import com.fabledsword.minstrel.api.endpoints.QuarantineApi import com.fabledsword.minstrel.cache.db.dao.CachedQuarantineDao import com.fabledsword.minstrel.cache.db.entities.CachedQuarantineEntity import com.fabledsword.minstrel.cache.mutations.MutationQueue +import com.fabledsword.minstrel.cache.mutations.WriteOutcome +import com.fabledsword.minstrel.cache.mutations.sendOrQueue import com.fabledsword.minstrel.models.QuarantineRef import com.fabledsword.minstrel.models.TrackRef import com.fabledsword.minstrel.models.wire.QuarantineMineWire @@ -13,10 +15,12 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.datetime.Clock +import retrofit2.HttpException import retrofit2.Retrofit import retrofit2.create import javax.inject.Inject import javax.inject.Singleton +import timber.log.Timber /** * Outcome of an `unflag` call — mirrors LikesRepository.toggleLike's @@ -94,15 +98,12 @@ class QuarantineRepository @Inject constructor( mutationQueue.enqueueQuarantineFlag(track.id, reason, notes) return FlagOutcome.QUEUED } - return try { - api.flag(FlagRequest(trackId = track.id, reason = reason, notes = notes)) - FlagOutcome.ACCEPTED - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - mutationQueue.enqueueQuarantineFlag(track.id, reason, notes) - FlagOutcome.QUEUED - } + val outcome = sendOrQueue( + send = { api.flag(FlagRequest(trackId = track.id, reason = reason, notes = notes)) }, + queue = { mutationQueue.enqueueQuarantineFlag(track.id, reason, notes) }, + onRefused = { e -> refused("flag", track.id, e) }, + ) + return if (outcome == WriteOutcome.Queued) FlagOutcome.QUEUED else FlagOutcome.ACCEPTED } suspend fun unflag(trackId: String): UnflagOutcome { @@ -111,15 +112,21 @@ class QuarantineRepository @Inject constructor( mutationQueue.enqueueQuarantineUnflag(trackId) return UnflagOutcome.QUEUED } - return try { - api.unflag(trackId) - UnflagOutcome.ACCEPTED - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - mutationQueue.enqueueQuarantineUnflag(trackId) - UnflagOutcome.QUEUED - } + val outcome = sendOrQueue( + send = { api.unflag(trackId) }, + queue = { mutationQueue.enqueueQuarantineUnflag(trackId) }, + onRefused = { e -> refused("unflag", trackId, e) }, + ) + return if (outcome == WriteOutcome.Queued) UnflagOutcome.QUEUED else UnflagOutcome.ACCEPTED + } + + /** + * The server said no (say, the track is gone). Nothing is queued, since a + * replay would be refused too; the next refresh shows the server's list. + */ + private fun refused(what: String, trackId: String, e: HttpException): WriteOutcome { + Timber.i(e, "quarantine: %s %s refused (%d)", what, trackId, e.code()) + return WriteOutcome.Refused } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/data/NormalizationRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/data/NormalizationRepository.kt index 52d2a57f..34a99fbb 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/data/NormalizationRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/data/NormalizationRepository.kt @@ -5,7 +5,8 @@ import com.fabledsword.minstrel.auth.AuthStore import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao import com.fabledsword.minstrel.cache.mutations.MutationKind import com.fabledsword.minstrel.cache.mutations.MutationQueue -import kotlinx.coroutines.CancellationException +import com.fabledsword.minstrel.cache.mutations.WriteOutcome +import com.fabledsword.minstrel.cache.mutations.sendOrQueue import kotlinx.coroutines.flow.StateFlow import retrofit2.Retrofit import retrofit2.create @@ -53,15 +54,13 @@ class NormalizationRepository @Inject constructor( mutationQueue.enqueueNormalizationSet(next) return } - try { - api.putNormalization(next) - } catch (e: CancellationException) { - throw e - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - Timber.i(e, "normalization: PUT failed; queued for replay") - mutationQueue.enqueueNormalizationSet(next) - } + sendOrQueue( + send = { api.putNormalization(next) }, + queue = { mutationQueue.enqueueNormalizationSet(next) }, + onRefused = { e -> + Timber.i(e, "normalization: PUT refused (%d)", e.code()) + WriteOutcome.Refused + }, + ) } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SendOrQueueTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SendOrQueueTest.kt new file mode 100644 index 00000000..7f2b7ec1 --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SendOrQueueTest.kt @@ -0,0 +1,54 @@ +package com.fabledsword.minstrel.cache.mutations + +import kotlinx.coroutines.test.runTest +import okhttp3.ResponseBody.Companion.toResponseBody +import org.junit.jupiter.api.Test +import retrofit2.HttpException +import retrofit2.Response +import java.io.IOException +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith + +/** + * The one rule for an offline-first write: queue what a later replay could + * get through (no answer, 5xx, 408, 429), and never queue what the server + * refused, since the replayer would only drop it. + */ +class SendOrQueueTest { + private var queued = 0 + + private fun httpError(status: Int) = HttpException(Response.error(status, "".toResponseBody())) + + private suspend fun attempt(failure: Throwable?, onRefused: ((HttpException) -> WriteOutcome)? = null) = + if (onRefused == null) { + sendOrQueue(send = { failure?.let { throw it } }, queue = { queued++ }) + } else { + sendOrQueue(send = { failure?.let { throw it } }, queue = { queued++ }, onRefused = onRefused) + } + + @Test + fun `a write the server takes is synced and not queued`() = runTest { + assertEquals(WriteOutcome.Synced, attempt(null)) + assertEquals(0, queued) + } + + @Test + fun `no answer, a server error, a timeout and too-many-requests are queued`() = runTest { + for (failure in listOf(IOException("offline"), httpError(503), httpError(408), httpError(429))) { + assertEquals(WriteOutcome.Queued, attempt(failure), "for $failure") + } + assertEquals(4, queued) + } + + @Test + fun `a refusal is not queued, and is thrown by default so the caller can say why`() = runTest { + assertFailsWith { attempt(httpError(403)) } + assertEquals(WriteOutcome.Refused, attempt(httpError(404)) { WriteOutcome.Refused }) + assertEquals(0, queued) + } + + @Test + fun `the replayer and the live write agree on what is worth retrying`() { + assertEquals(listOf(408, 429, 500, 503), listOf(400, 403, 404, 408, 409, 429, 500, 503).filter(::isRetryableStatus)) + } +}