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
|
Outcome.RETRY
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 4xx are permanent except the two "retry me" statuses. */
|
/** A refusal that a replay would only get again ([isRetryableStatus]'s complement). */
|
||||||
private fun isPermanent(code: Int): Boolean =
|
private fun isPermanent(code: Int): Boolean = !isRetryableStatus(code)
|
||||||
code in HTTP_CLIENT_ERR_MIN..HTTP_CLIENT_ERR_MAX &&
|
|
||||||
code != HTTP_TIMEOUT && code != HTTP_TOO_MANY
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the outcome of replaying one row. SENT on a 2xx; DROP for an
|
* 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
|
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
|
package com.fabledsword.minstrel.likes.data
|
||||||
|
|
||||||
|
import com.fabledsword.minstrel.cache.mutations.WriteOutcome
|
||||||
import com.fabledsword.minstrel.cache.mutations.likeToggleKey
|
import com.fabledsword.minstrel.cache.mutations.likeToggleKey
|
||||||
import com.fabledsword.minstrel.api.endpoints.LikesApi
|
import com.fabledsword.minstrel.api.endpoints.LikesApi
|
||||||
import com.fabledsword.minstrel.auth.AuthController
|
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.dao.CachedTrackDao
|
||||||
import com.fabledsword.minstrel.cache.db.entities.CachedLikeEntity
|
import com.fabledsword.minstrel.cache.db.entities.CachedLikeEntity
|
||||||
import com.fabledsword.minstrel.cache.mutations.MutationQueue
|
import com.fabledsword.minstrel.cache.mutations.MutationQueue
|
||||||
|
import com.fabledsword.minstrel.cache.mutations.sendOrQueue
|
||||||
import com.fabledsword.minstrel.di.ApplicationScope
|
import com.fabledsword.minstrel.di.ApplicationScope
|
||||||
import com.fabledsword.minstrel.library.data.toDomain
|
import com.fabledsword.minstrel.library.data.toDomain
|
||||||
import com.fabledsword.minstrel.models.AlbumRef
|
import com.fabledsword.minstrel.models.AlbumRef
|
||||||
@@ -29,6 +31,7 @@ import retrofit2.create
|
|||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
import kotlin.time.Duration.Companion.milliseconds
|
import kotlin.time.Duration.Companion.milliseconds
|
||||||
|
import timber.log.Timber
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cache-first reads + offline-first writes for likes.
|
* 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.
|
// 2. Best-effort REST call; 3. enqueue on failure.
|
||||||
val kindPath = serverPathFor(entityType)
|
val kindPath = serverPathFor(entityType)
|
||||||
return try {
|
// A refusal isn't surfaced: the heart buttons don't wait on this call,
|
||||||
if (desiredState) api.like(kindPath, entityId) else api.unlike(kindPath, entityId)
|
// and the next likes refresh puts the server's answer back on screen.
|
||||||
true
|
return sendOrQueue(
|
||||||
} catch (
|
send = { if (desiredState) api.like(kindPath, entityId) else api.unlike(kindPath, entityId) },
|
||||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
queue = { mutationQueue.enqueueLikeToggle(entityType, entityId, desiredState) },
|
||||||
) {
|
onRefused = { e ->
|
||||||
// Intentional swallow: the queue replays this later; surfacing
|
Timber.i(e, "likes: %s %s refused (%d)", entityType, entityId, e.code())
|
||||||
// the network error here would force callers (UI) to handle it
|
WriteOutcome.Refused
|
||||||
// even though it's already been buffered.
|
},
|
||||||
mutationQueue.enqueueLikeToggle(entityType, entityId, desiredState)
|
) == WriteOutcome.Synced
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+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.MutationKind
|
||||||
import com.fabledsword.minstrel.cache.mutations.MutationQueue
|
import com.fabledsword.minstrel.cache.mutations.MutationQueue
|
||||||
import com.fabledsword.minstrel.cache.mutations.NotificationSettingPayload
|
import com.fabledsword.minstrel.cache.mutations.NotificationSettingPayload
|
||||||
|
import com.fabledsword.minstrel.cache.mutations.WriteOutcome
|
||||||
import com.fabledsword.minstrel.cache.mutations.notificationSettingChange
|
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.Flow
|
||||||
import kotlinx.coroutines.flow.map
|
import kotlinx.coroutines.flow.map
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
@@ -61,16 +62,14 @@ class NotificationSettingsRepository @Inject constructor(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
val change = notificationSettingChange(payload) ?: return
|
val change = notificationSettingChange(payload) ?: return
|
||||||
try {
|
sendOrQueue(
|
||||||
save(api.putSettings(PutNotificationSettingsBody(listOf(change))))
|
send = { save(api.putSettings(PutNotificationSettingsBody(listOf(change)))) },
|
||||||
} catch (e: CancellationException) {
|
queue = { mutationQueue.enqueueNotificationSettingSet(payload) },
|
||||||
throw e
|
onRefused = { e ->
|
||||||
} catch (
|
Timber.i(e, "notification settings: PUT refused (%d)", e.code())
|
||||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
WriteOutcome.Refused
|
||||||
) {
|
},
|
||||||
Timber.i(e, "notification settings: PUT failed; queued")
|
)
|
||||||
mutationQueue.enqueueNotificationSettingSet(payload)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun current(): NotificationSettingsWire? = dao.getSettings()?.let(::decode)
|
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.dao.CachedNotificationDao
|
||||||
import com.fabledsword.minstrel.cache.db.entities.CachedNotificationEntity
|
import com.fabledsword.minstrel.cache.db.entities.CachedNotificationEntity
|
||||||
import com.fabledsword.minstrel.cache.mutations.MutationQueue
|
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.Flow
|
||||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
import kotlinx.datetime.Clock
|
import kotlinx.datetime.Clock
|
||||||
@@ -52,24 +53,12 @@ class NotificationsRepository @Inject constructor(
|
|||||||
|
|
||||||
suspend fun markRead(id: String) {
|
suspend fun markRead(id: String) {
|
||||||
dao.markRead(id, Clock.System.now())
|
dao.markRead(id, Clock.System.now())
|
||||||
try {
|
// A refusal (404: trimmed or gone server-side) leaves nothing to mark.
|
||||||
api.markRead(id)
|
sendOrQueue(
|
||||||
} catch (e: CancellationException) {
|
send = { api.markRead(id) },
|
||||||
throw e
|
queue = { mutationQueue.enqueueNotificationRead(id) },
|
||||||
} catch (e: HttpException) {
|
onRefused = { e -> refused("mark read", e) },
|
||||||
// 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)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -80,16 +69,16 @@ class NotificationsRepository @Inject constructor(
|
|||||||
suspend fun markAllRead() {
|
suspend fun markAllRead() {
|
||||||
val upTo = readAllCutoff(dao.getAll().map { it.createdAt })?.toString()
|
val upTo = readAllCutoff(dao.getAll().map { it.createdAt })?.toString()
|
||||||
dao.markAllRead(Clock.System.now())
|
dao.markAllRead(Clock.System.now())
|
||||||
try {
|
sendOrQueue(
|
||||||
api.readAll(ReadAllBody(upTo = upTo))
|
send = { api.readAll(ReadAllBody(upTo = upTo)) },
|
||||||
} catch (e: CancellationException) {
|
queue = { mutationQueue.enqueueNotificationsReadAll(upTo) },
|
||||||
throw e
|
onRefused = { e -> refused("mark all read", e) },
|
||||||
} catch (
|
)
|
||||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
}
|
||||||
) {
|
|
||||||
Timber.i(e, "notifications: mark all read failed; queued")
|
private fun refused(what: String, e: HttpException): WriteOutcome {
|
||||||
mutationQueue.enqueueNotificationsReadAll(upTo)
|
Timber.i(e, "notifications: %s refused (%d)", what, e.code())
|
||||||
}
|
return WriteOutcome.Refused
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The page the device holds, newest first. */
|
/** The page the device holds, newest first. */
|
||||||
@@ -103,8 +92,6 @@ class NotificationsRepository @Inject constructor(
|
|||||||
companion object {
|
companion object {
|
||||||
/** The newest page the device keeps; older notices stay on the server. */
|
/** The newest page the device keeps; older notices stay on the server. */
|
||||||
const val PAGE_SIZE = 50
|
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.ReorderTracksRequest
|
||||||
import com.fabledsword.minstrel.api.endpoints.UpdatePlaylistRequest
|
import com.fabledsword.minstrel.api.endpoints.UpdatePlaylistRequest
|
||||||
import com.fabledsword.minstrel.auth.AuthController
|
import com.fabledsword.minstrel.auth.AuthController
|
||||||
|
import com.fabledsword.minstrel.cache.mutations.WriteOutcome
|
||||||
|
import com.fabledsword.minstrel.cache.mutations.sendOrQueue
|
||||||
import retrofit2.HttpException
|
import retrofit2.HttpException
|
||||||
import java.net.HttpURLConnection
|
import java.net.HttpURLConnection
|
||||||
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao
|
import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao
|
||||||
@@ -33,7 +35,6 @@ import kotlinx.coroutines.flow.flowOf
|
|||||||
import kotlinx.coroutines.flow.map
|
import kotlinx.coroutines.flow.map
|
||||||
import retrofit2.Retrofit
|
import retrofit2.Retrofit
|
||||||
import retrofit2.create
|
import retrofit2.create
|
||||||
import java.io.IOException
|
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
@@ -273,27 +274,8 @@ class PlaylistsRepository @Inject constructor(
|
|||||||
queue = { mutationQueue.enqueuePlaylistReorder(PlaylistReorderPayload(playlistId, trackIds)) },
|
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
|
* Snapshot of a playlist + its per-track display fields, as returned
|
||||||
* by `PlaylistsRepository.refreshDetail`. UI uses this directly for
|
* 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.composables.icons.lucide.Shuffle
|
||||||
import com.fabledsword.minstrel.api.ErrorCopy
|
import com.fabledsword.minstrel.api.ErrorCopy
|
||||||
import com.fabledsword.minstrel.auth.AuthController
|
import com.fabledsword.minstrel.auth.AuthController
|
||||||
|
import com.fabledsword.minstrel.cache.mutations.WriteOutcome
|
||||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||||
import com.fabledsword.minstrel.connectivity.recoveries
|
import com.fabledsword.minstrel.connectivity.recoveries
|
||||||
import com.fabledsword.minstrel.events.EventsStream
|
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.likes.data.LikesRepository
|
||||||
import com.fabledsword.minstrel.playlists.data.PlaylistDetailRef
|
import com.fabledsword.minstrel.playlists.data.PlaylistDetailRef
|
||||||
import com.fabledsword.minstrel.playlists.data.PlaylistsRepository
|
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.entryKeys
|
||||||
import com.fabledsword.minstrel.playlists.data.toPlayableTrackRefs
|
import com.fabledsword.minstrel.playlists.data.toPlayableTrackRefs
|
||||||
import com.fabledsword.minstrel.playlists.data.trackOrder
|
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.Lucide
|
||||||
import com.composables.icons.lucide.Plus
|
import com.composables.icons.lucide.Plus
|
||||||
import com.fabledsword.minstrel.api.ErrorCopy
|
import com.fabledsword.minstrel.api.ErrorCopy
|
||||||
|
import com.fabledsword.minstrel.cache.mutations.WriteOutcome
|
||||||
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
import com.fabledsword.minstrel.connectivity.NetworkStatusController
|
||||||
import com.fabledsword.minstrel.connectivity.ServerHealth
|
import com.fabledsword.minstrel.connectivity.ServerHealth
|
||||||
import com.fabledsword.minstrel.connectivity.recoveries
|
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.nav.Playlists
|
||||||
import com.fabledsword.minstrel.player.PlayerController
|
import com.fabledsword.minstrel.player.PlayerController
|
||||||
import com.fabledsword.minstrel.playlists.data.PlaylistsRepository
|
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.playlists.data.playPlaylistShuffled
|
||||||
import com.fabledsword.minstrel.shared.UiState
|
import com.fabledsword.minstrel.shared.UiState
|
||||||
import com.fabledsword.minstrel.shared.asCacheFirstStateFlow
|
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.dao.CachedQuarantineDao
|
||||||
import com.fabledsword.minstrel.cache.db.entities.CachedQuarantineEntity
|
import com.fabledsword.minstrel.cache.db.entities.CachedQuarantineEntity
|
||||||
import com.fabledsword.minstrel.cache.mutations.MutationQueue
|
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.QuarantineRef
|
||||||
import com.fabledsword.minstrel.models.TrackRef
|
import com.fabledsword.minstrel.models.TrackRef
|
||||||
import com.fabledsword.minstrel.models.wire.QuarantineMineWire
|
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.first
|
||||||
import kotlinx.coroutines.flow.map
|
import kotlinx.coroutines.flow.map
|
||||||
import kotlinx.datetime.Clock
|
import kotlinx.datetime.Clock
|
||||||
|
import retrofit2.HttpException
|
||||||
import retrofit2.Retrofit
|
import retrofit2.Retrofit
|
||||||
import retrofit2.create
|
import retrofit2.create
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
import timber.log.Timber
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Outcome of an `unflag` call — mirrors LikesRepository.toggleLike's
|
* Outcome of an `unflag` call — mirrors LikesRepository.toggleLike's
|
||||||
@@ -94,15 +98,12 @@ class QuarantineRepository @Inject constructor(
|
|||||||
mutationQueue.enqueueQuarantineFlag(track.id, reason, notes)
|
mutationQueue.enqueueQuarantineFlag(track.id, reason, notes)
|
||||||
return FlagOutcome.QUEUED
|
return FlagOutcome.QUEUED
|
||||||
}
|
}
|
||||||
return try {
|
val outcome = sendOrQueue(
|
||||||
api.flag(FlagRequest(trackId = track.id, reason = reason, notes = notes))
|
send = { api.flag(FlagRequest(trackId = track.id, reason = reason, notes = notes)) },
|
||||||
FlagOutcome.ACCEPTED
|
queue = { mutationQueue.enqueueQuarantineFlag(track.id, reason, notes) },
|
||||||
} catch (
|
onRefused = { e -> refused("flag", track.id, e) },
|
||||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
)
|
||||||
) {
|
return if (outcome == WriteOutcome.Queued) FlagOutcome.QUEUED else FlagOutcome.ACCEPTED
|
||||||
mutationQueue.enqueueQuarantineFlag(track.id, reason, notes)
|
|
||||||
FlagOutcome.QUEUED
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun unflag(trackId: String): UnflagOutcome {
|
suspend fun unflag(trackId: String): UnflagOutcome {
|
||||||
@@ -111,15 +112,21 @@ class QuarantineRepository @Inject constructor(
|
|||||||
mutationQueue.enqueueQuarantineUnflag(trackId)
|
mutationQueue.enqueueQuarantineUnflag(trackId)
|
||||||
return UnflagOutcome.QUEUED
|
return UnflagOutcome.QUEUED
|
||||||
}
|
}
|
||||||
return try {
|
val outcome = sendOrQueue(
|
||||||
api.unflag(trackId)
|
send = { api.unflag(trackId) },
|
||||||
UnflagOutcome.ACCEPTED
|
queue = { mutationQueue.enqueueQuarantineUnflag(trackId) },
|
||||||
} catch (
|
onRefused = { e -> refused("unflag", trackId, e) },
|
||||||
@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable,
|
)
|
||||||
) {
|
return if (outcome == WriteOutcome.Queued) UnflagOutcome.QUEUED else UnflagOutcome.ACCEPTED
|
||||||
mutationQueue.enqueueQuarantineUnflag(trackId)
|
}
|
||||||
UnflagOutcome.QUEUED
|
|
||||||
}
|
/**
|
||||||
|
* 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.db.dao.CachedMutationDao
|
||||||
import com.fabledsword.minstrel.cache.mutations.MutationKind
|
import com.fabledsword.minstrel.cache.mutations.MutationKind
|
||||||
import com.fabledsword.minstrel.cache.mutations.MutationQueue
|
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 kotlinx.coroutines.flow.StateFlow
|
||||||
import retrofit2.Retrofit
|
import retrofit2.Retrofit
|
||||||
import retrofit2.create
|
import retrofit2.create
|
||||||
@@ -53,15 +54,13 @@ class NormalizationRepository @Inject constructor(
|
|||||||
mutationQueue.enqueueNormalizationSet(next)
|
mutationQueue.enqueueNormalizationSet(next)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
try {
|
sendOrQueue(
|
||||||
api.putNormalization(next)
|
send = { api.putNormalization(next) },
|
||||||
} catch (e: CancellationException) {
|
queue = { mutationQueue.enqueueNormalizationSet(next) },
|
||||||
throw e
|
onRefused = { e ->
|
||||||
} catch (
|
Timber.i(e, "normalization: PUT refused (%d)", e.code())
|
||||||
@Suppress("TooGenericExceptionCaught") e: Throwable,
|
WriteOutcome.Refused
|
||||||
) {
|
},
|
||||||
Timber.i(e, "normalization: PUT failed; queued for replay")
|
)
|
||||||
mutationQueue.enqueueNormalizationSet(next)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+54
@@ -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<Unit>(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<HttpException> { 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))
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user