diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaylistsApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaylistsApi.kt index 79d1c98e..520ab623 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaylistsApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaylistsApi.kt @@ -93,12 +93,14 @@ interface PlaylistsApi { } /** - * POST /api/playlists/{id}/tracks body. The server expects snake_case - * `track_ids`. + * POST /api/playlists/{id}/tracks body. [requestId] names the append: the + * server applies an id once per playlist, so sending it again after a lost + * reply adds nothing more. */ @Serializable data class AppendTracksRequest( @SerialName("track_ids") val trackIds: List, + @SerialName("request_id") val requestId: String? = null, ) /** diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt index 3453248f..c2ea1ac1 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt @@ -131,15 +131,9 @@ class MutationQueue @Inject constructor( ), ) - suspend fun enqueuePlaylistAppend( - playlistId: String, - trackIds: List, - ): Long = insertUserDriven( + suspend fun enqueuePlaylistAppend(payload: PlaylistAppendPayload): Long = insertUserDriven( MutationKind.PLAYLIST_APPEND, - json.encodeToString( - PlaylistAppendPayload.serializer(), - PlaylistAppendPayload(playlistId, trackIds), - ), + json.encodeToString(PlaylistAppendPayload.serializer(), payload), ) suspend fun enqueuePlaylistCreate(payload: PlaylistCreatePayload): Long = insertUserDriven( @@ -294,11 +288,18 @@ data class QuarantineUnflagPayload(val trackId: String) /** The key [MutationQueue.pendingLikeStates] files a like toggle under. */ fun likeToggleKey(entityType: String, entityId: String): String = "$entityType:$entityId" -/** Persisted payload for `MutationKind.PLAYLIST_APPEND`: the track IDs to append to one playlist. */ +/** + * Persisted payload for `MutationKind.PLAYLIST_APPEND`: the track IDs to + * append to one playlist. [requestId] is the id the live send carried, so + * the server can tell a replay of an append it already applied (its reply + * was lost) from a new one. Rows queued before it existed have none and + * append on every send, as they always did. + */ @Serializable data class PlaylistAppendPayload( val playlistId: String, val trackIds: List, + val requestId: String? = null, ) /** Persisted payload for `MutationKind.PLAYLIST_CREATE`; [id] is the one the app chose. */ 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 f0541450..96c1f400 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 @@ -252,7 +252,10 @@ class MutationReplayer @Inject constructor( when (row.kind) { MutationKind.PLAYLIST_APPEND -> { val p = json.decodeFromString(PlaylistAppendPayload.serializer(), payload) - playlistsApi.appendTracks(p.playlistId, AppendTracksRequest(trackIds = p.trackIds)) + playlistsApi.appendTracks( + p.playlistId, + AppendTracksRequest(trackIds = p.trackIds, requestId = p.requestId), + ) } MutationKind.PLAYLIST_CREATE -> { val p = json.decodeFromString(PlaylistCreatePayload.serializer(), payload) 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 3312f442..3c98f881 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 @@ -16,6 +16,7 @@ import com.fabledsword.minstrel.cache.db.dao.PlaylistCachedCount import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistEntity import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistTrackEntity import com.fabledsword.minstrel.cache.mutations.MutationQueue +import com.fabledsword.minstrel.cache.mutations.PlaylistAppendPayload import com.fabledsword.minstrel.cache.mutations.PlaylistCreatePayload import com.fabledsword.minstrel.cache.mutations.PlaylistRemoveTrackPayload import com.fabledsword.minstrel.cache.mutations.PlaylistReorderPayload @@ -195,16 +196,19 @@ class PlaylistsRepository @Inject constructor( /** * Append a single track to a user-owned playlist. The (playlistId, * trackId) key means a song already in the list keeps its place in - * Room. + * Room. The send and its queued replay carry one request id, so a + * replay of a send that reached the server, but whose reply didn't + * reach the phone, doesn't add the song a second time. */ suspend fun appendTrack(playlistId: String, trackId: String): WriteOutcome { val nextPos = (playlistTrackDao.maxPosition(playlistId) ?: -1) + 1 playlistTrackDao.insertOrIgnore( CachedPlaylistTrackEntity(playlistId = playlistId, trackId = trackId, position = nextPos), ) + val append = PlaylistAppendPayload(playlistId, listOf(trackId), requestId = UUID.randomUUID().toString()) return sendOrQueue( - send = { api.appendTracks(playlistId, AppendTracksRequest(trackIds = listOf(trackId))) }, - queue = { mutationQueue.enqueuePlaylistAppend(playlistId, listOf(trackId)) }, + send = { api.appendTracks(playlistId, AppendTracksRequest(append.trackIds, append.requestId)) }, + queue = { mutationQueue.enqueuePlaylistAppend(append) }, ) } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryWritesTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryWritesTest.kt index dcc9b9f8..4abc740c 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryWritesTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryWritesTest.kt @@ -1,5 +1,6 @@ package com.fabledsword.minstrel.playlists.data +import com.fabledsword.minstrel.api.endpoints.AppendTracksRequest import com.fabledsword.minstrel.api.endpoints.CreatePlaylistRequest import com.fabledsword.minstrel.api.endpoints.PlaylistsApi import com.fabledsword.minstrel.api.endpoints.ReorderTracksRequest @@ -8,6 +9,7 @@ import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistEntity import com.fabledsword.minstrel.cache.mutations.MutationQueue +import com.fabledsword.minstrel.cache.mutations.PlaylistAppendPayload import com.fabledsword.minstrel.cache.mutations.PlaylistCreatePayload import com.fabledsword.minstrel.cache.mutations.PlaylistRemoveTrackPayload import com.fabledsword.minstrel.cache.mutations.PlaylistReorderPayload @@ -28,6 +30,7 @@ import retrofit2.Response import retrofit2.Retrofit import java.io.IOException import kotlin.test.assertEquals +import kotlin.test.assertNotNull import kotlin.test.assertTrue /** @@ -75,6 +78,20 @@ class PlaylistsRepositoryWritesTest { assertEquals(PlaylistCreatePayload(id = id, name = "Road Songs"), queued.captured) } + @Test + fun `an append whose reply is lost is queued under the request id it was sent with`() = runTest { + val sent = slot() + coEvery { api.appendTracks("p1", capture(sent)) } throws IOException("reply lost") + val queued = slot() + coEvery { queue.enqueuePlaylistAppend(capture(queued)) } returns 1L + + val outcome = repo.appendTrack("p1", "t1") + + assertEquals(WriteOutcome.Queued, outcome) + assertNotNull(sent.captured.requestId) + assertEquals(PlaylistAppendPayload("p1", listOf("t1"), sent.captured.requestId), queued.captured) + } + @Test fun `a removal made offline is queued with the song expected at that place`() = runTest { coEvery { api.removeTrack(any(), any(), any()) } throws IOException("offline") diff --git a/internal/api/playlists.go b/internal/api/playlists.go index 01a970c4..079ec3c8 100644 --- a/internal/api/playlists.go +++ b/internal/api/playlists.go @@ -296,6 +296,10 @@ func (h *handlers) handleDeletePlaylist(w http.ResponseWriter, r *http.Request) type appendTracksBody struct { TrackIDs []string `json:"track_ids"` + // RequestID names this append, so a client that sends it again (a + // queued write replayed after its reply was lost) adds nothing more. + // Optional: without it, every send appends. + RequestID string `json:"request_id"` } // handleAppendTracks implements POST /api/playlists/{id}/tracks. Owner @@ -318,7 +322,14 @@ func (h *handlers) handleAppendTracks(w http.ResponseWriter, r *http.Request) { if !ok { return } - if err := h.playlists.AppendTracks(r.Context(), caller.ID, playlistID, trackIDs); err != nil { + var requestID pgtype.UUID + if body.RequestID != "" { + if requestID, ok = parseUUID(body.RequestID); !ok { + writeErr(w, apierror.BadRequest("bad_request", fmt.Sprintf("invalid request id %q", body.RequestID))) + return + } + } + if err := h.playlists.AppendTracksOnce(r.Context(), caller.ID, playlistID, trackIDs, requestID); err != nil { h.writePlaylistErr(w, err, "append tracks") return } diff --git a/internal/backup/tables.go b/internal/backup/tables.go index 62aa83e1..608cd706 100644 --- a/internal/backup/tables.go +++ b/internal/backup/tables.go @@ -109,10 +109,11 @@ var Tables = []Table{ // Excluded is every table a backup leaves out, with the reason. var Excluded = map[string]string{ - "schema_migrations": "the restored server's own migrations write it; the backup's schema version is in its manifest", - "sessions": "sign-ins; everyone signs in again on the restored server", - "password_resets": "one-time reset links, which expire within hours", - "user_invites": "open sign-up links; an admin sends an invite again from the restored server", + "schema_migrations": "the restored server's own migrations write it; the backup's schema version is in its manifest", + "sessions": "sign-ins; everyone signs in again on the restored server", + "password_resets": "one-time reset links, which expire within hours", + "playlist_append_requests": "replay guards for appends a phone sent; the restored server has received none of them", + "user_invites": "open sign-up links; an admin sends an invite again from the restored server", "track_fingerprints": "computed from the music files", "track_loudness": "computed from the music files", diff --git a/internal/db/dbq/models.go b/internal/db/dbq/models.go index 7ea40a32..784c5b9c 100644 --- a/internal/db/dbq/models.go +++ b/internal/db/dbq/models.go @@ -467,6 +467,12 @@ type Playlist struct { ShelfRank int32 } +type PlaylistAppendRequest struct { + PlaylistID pgtype.UUID + RequestID pgtype.UUID + CreatedAt pgtype.Timestamptz +} + type PlaylistTrack struct { PlaylistID pgtype.UUID Position int32 diff --git a/internal/db/dbq/playlists.sql.go b/internal/db/dbq/playlists.sql.go index 8a67c78a..ed88fac9 100644 --- a/internal/db/dbq/playlists.sql.go +++ b/internal/db/dbq/playlists.sql.go @@ -513,6 +513,39 @@ func (q *Queries) ListUserPlaylistIDsForOwner(ctx context.Context, userID pgtype return items, nil } +const prunePlaylistAppendRequests = `-- name: PrunePlaylistAppendRequests :exec +DELETE FROM playlist_append_requests +WHERE playlist_id = $1 AND created_at < now() - interval '30 days' +` + +// Forgets the playlist's append request ids older than 30 days, by which +// time any queued replay of them has long since been sent. +func (q *Queries) PrunePlaylistAppendRequests(ctx context.Context, playlistID pgtype.UUID) error { + _, err := q.db.Exec(ctx, prunePlaylistAppendRequests, playlistID) + return err +} + +const recordPlaylistAppendRequest = `-- name: RecordPlaylistAppendRequest :execrows +INSERT INTO playlist_append_requests (playlist_id, request_id) +VALUES ($1::uuid, $2::uuid) +ON CONFLICT DO NOTHING +` + +type RecordPlaylistAppendRequestParams struct { + PlaylistID pgtype.UUID + RequestID pgtype.UUID +} + +// Claims a client's append request id for the playlist. No row affected +// means the id was already applied: the append is a replay. +func (q *Queries) RecordPlaylistAppendRequest(ctx context.Context, arg RecordPlaylistAppendRequestParams) (int64, error) { + result, err := q.db.Exec(ctx, recordPlaylistAppendRequest, arg.PlaylistID, arg.RequestID) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + const renumberPlaylistTracksAfter = `-- name: RenumberPlaylistTracksAfter :exec UPDATE playlist_tracks SET position = position - 1 diff --git a/internal/db/migrations/0113_playlist_append_requests.down.sql b/internal/db/migrations/0113_playlist_append_requests.down.sql new file mode 100644 index 00000000..b05f6403 --- /dev/null +++ b/internal/db/migrations/0113_playlist_append_requests.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS playlist_append_requests; diff --git a/internal/db/migrations/0113_playlist_append_requests.up.sql b/internal/db/migrations/0113_playlist_append_requests.up.sql new file mode 100644 index 00000000..a33af9fb --- /dev/null +++ b/internal/db/migrations/0113_playlist_append_requests.up.sql @@ -0,0 +1,13 @@ +-- An append the phone sent but never heard back about (a timeout, the app +-- killed mid-request) stays in its offline queue and is sent again. An +-- append is an action, not a state, so the second send would add the songs +-- a second time. The phone now names each append with a request id, and +-- the server keeps the ids it has applied here: a send whose id is already +-- recorded for the playlist changes nothing. Rows older than 30 days are +-- pruned as new appends arrive; a queued write is replayed long before that. +CREATE TABLE playlist_append_requests ( + playlist_id uuid NOT NULL REFERENCES playlists(id) ON DELETE CASCADE, + request_id uuid NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (playlist_id, request_id) +); diff --git a/internal/db/queries/playlists.sql b/internal/db/queries/playlists.sql index 36cbf4cf..c33523b7 100644 --- a/internal/db/queries/playlists.sql +++ b/internal/db/queries/playlists.sql @@ -113,6 +113,19 @@ JOIN artists ON artists.id = t.artist_id WHERE t.id = sqlc.arg(track_id)::uuid RETURNING *; +-- name: RecordPlaylistAppendRequest :execrows +-- Claims a client's append request id for the playlist. No row affected +-- means the id was already applied: the append is a replay. +INSERT INTO playlist_append_requests (playlist_id, request_id) +VALUES (sqlc.arg(playlist_id)::uuid, sqlc.arg(request_id)::uuid) +ON CONFLICT DO NOTHING; + +-- name: PrunePlaylistAppendRequests :exec +-- Forgets the playlist's append request ids older than 30 days, by which +-- time any queued replay of them has long since been sent. +DELETE FROM playlist_append_requests +WHERE playlist_id = $1 AND created_at < now() - interval '30 days'; + -- name: DeletePlaylistTrack :exec -- Two-step: delete the row at `position`, then renumber subsequent rows -- to close the gap. The renumber is a single UPDATE; the service layer diff --git a/internal/dbtest/reset.go b/internal/dbtest/reset.go index 1d35d06b..db47fdc7 100644 --- a/internal/dbtest/reset.go +++ b/internal/dbtest/reset.go @@ -62,6 +62,7 @@ var dataTables = []string{ // so nothing cascades to them. A leftover tag row would make a // candidate look enriched to the next test, and a leftover state row // would make it look already-settled and thus ineligible. + "playlist_append_requests", "playlist_tracks", "playlists", "play_queues", diff --git a/internal/playlists/offline_replay_test.go b/internal/playlists/offline_replay_test.go index 472a44ce..cd057db9 100644 --- a/internal/playlists/offline_replay_test.go +++ b/internal/playlists/offline_replay_test.go @@ -160,3 +160,50 @@ func trackTitles(d *playlists.PlaylistDetail) []string { } return out } + +func TestAppendTracksOnce_ASecondSendWithTheSameRequestAddsNothing(t *testing.T) { + pool := dbtest.Pool(t) + user := seedUser(t, pool, "alice") + a := seedTrack(t, pool, "A", "Artist") + b := seedTrack(t, pool, "B", "Artist") + svc := playlists.NewService(pool, nil, t.TempDir()) + ctx := context.Background() + pl, _ := svc.Create(ctx, user.ID, "Test", "", false) + sent := randomUUID() + + for range 2 { + if err := svc.AppendTracksOnce(ctx, user.ID, pl.ID, []pgtype.UUID{a.ID}, sent); err != nil { + t.Fatalf("append A: %v", err) + } + } + // A new request is a new append, even of the same song. + if err := svc.AppendTracksOnce(ctx, user.ID, pl.ID, []pgtype.UUID{a.ID, b.ID}, randomUUID()); err != nil { + t.Fatalf("append A, B: %v", err) + } + got, _ := svc.Get(ctx, user.ID, pl.ID) + if titles := trackTitles(got); !slices.Equal(titles, []string{"A", "A", "B"}) { + t.Errorf("tracks = %v, want A, A, B", titles) + } +} + +func TestAppendTracksOnce_AFailedAppendDoesNotUseUpItsRequest(t *testing.T) { + pool := dbtest.Pool(t) + user := seedUser(t, pool, "alice") + a := seedTrack(t, pool, "A", "Artist") + svc := playlists.NewService(pool, nil, t.TempDir()) + ctx := context.Background() + pl, _ := svc.Create(ctx, user.ID, "Test", "", false) + sent := randomUUID() + + err := svc.AppendTracksOnce(ctx, user.ID, pl.ID, []pgtype.UUID{a.ID, randomUUID()}, sent) + if !errors.Is(err, playlists.ErrTrackNotFound) { + t.Fatalf("append with a missing track: %v, want ErrTrackNotFound", err) + } + if err := svc.AppendTracksOnce(ctx, user.ID, pl.ID, []pgtype.UUID{a.ID}, sent); err != nil { + t.Fatalf("append A: %v", err) + } + got, _ := svc.Get(ctx, user.ID, pl.ID) + if titles := trackTitles(got); !slices.Equal(titles, []string{"A"}) { + t.Errorf("tracks = %v, want A: the failed send rolled back with its request id", titles) + } +} diff --git a/internal/playlists/service.go b/internal/playlists/service.go index bc76956a..c07fc57d 100644 --- a/internal/playlists/service.go +++ b/internal/playlists/service.go @@ -390,14 +390,48 @@ func editable(ctx context.Context, q *dbq.Queries, callerID, playlistID pgtype.U // are populated from the tracks/albums/artists join at insert time. // Triggers cover regeneration after. func (s *Service) AppendTracks(ctx context.Context, callerID, playlistID pgtype.UUID, trackIDs []pgtype.UUID) error { + return s.AppendTracksOnce(ctx, callerID, playlistID, trackIDs, pgtype.UUID{}) +} + +// AppendTracksOnce is AppendTracks for a client that may send the same +// append twice: a phone replaying a queued append whose first send reached +// the server but whose reply was lost. A valid requestID is recorded with +// the append, in the same transaction, and a later send with the same id +// for the same playlist changes nothing. Without a requestID it appends +// every time. +func (s *Service) AppendTracksOnce(ctx context.Context, callerID, playlistID pgtype.UUID, trackIDs []pgtype.UUID, requestID pgtype.UUID) error { if len(trackIDs) == 0 { return fmt.Errorf("%w: at least one track id required", ErrInvalidInput) } return s.changeTracks(ctx, callerID, playlistID, func(tx pgx.Tx) error { + if requestID.Valid { + fresh, err := claimAppendRequest(ctx, tx, playlistID, requestID) + if err != nil || !fresh { + return err + } + } return appendTracks(ctx, tx, playlistID, trackIDs) }) } +// claimAppendRequest records requestID as applied to the playlist, and +// reports whether it was new. Old ids are forgotten here too, so the table +// stays as small as the playlist's last month of appends. +func claimAppendRequest(ctx context.Context, tx pgx.Tx, playlistID, requestID pgtype.UUID) (bool, error) { + q := dbq.New(tx) + if err := q.PrunePlaylistAppendRequests(ctx, playlistID); err != nil { + return false, fmt.Errorf("prune append requests: %w", err) + } + n, err := q.RecordPlaylistAppendRequest(ctx, dbq.RecordPlaylistAppendRequestParams{ + PlaylistID: playlistID, + RequestID: requestID, + }) + if err != nil { + return false, fmt.Errorf("record append request: %w", err) + } + return n == 1, nil +} + // ReplaceTracks makes trackIDs the playlist's whole track list, in order; // an empty list empties it. The old list goes only if every new track // exists.