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 <noreply@anthropic.com>
This commit is contained in:
+2
-11
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+58
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+10
-11
@@ -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)
|
||||
|
||||
+18
-31
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-20
@@ -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
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
+25
-18
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+10
-11
@@ -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
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user