release / go (push) Successful in 1m56s
release / web (push) Successful in 1m18s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m0s
release / android (push) Successful in 4m20s
release / Build signed APK (push) Successful in 4m52s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 25s
release / Verify release artifacts (tag releases only) (push) Skipped
- library.ProbeDurationMs and IsAudioFile, and db.MigrationsFS, had no callers. - The delta sync logged and hydrated like and playlist changes on every like, playlist edit and duplicate merge, including a GetPlaylistsByIDs query per sync. Android applies only artists, albums and tracks, and the web doesn't sync; likes and playlists reach both through their own endpoints and live events. The like and playlist-entry deletes also went to every caller unscoped, user ids included. They are no longer written or served, and migration 0112 clears the rows already logged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
210 lines
6.2 KiB
Go
210 lines
6.2 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
|
|
"git.fabledsword.com/bvandeusen/minstrel/internal/apierror"
|
|
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
|
|
"git.fabledsword.com/bvandeusen/minstrel/internal/library"
|
|
syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync"
|
|
)
|
|
|
|
// SyncBatchLimit caps the number of change rows returned per call.
|
|
// Clients that need more loop with the returned cursor.
|
|
const SyncBatchLimit = 1000
|
|
|
|
// syncResponse is the wire shape returned by GET /api/library/sync.
|
|
// upserts and deletes are separated by entity type so clients can apply
|
|
// them to typed local tables. cursor is the largest library_changes.id
|
|
// the server returned in this batch — clients pass it back as `since`
|
|
// next time.
|
|
type syncResponse struct {
|
|
Cursor int64 `json:"cursor"`
|
|
Upserts map[string][]json.RawMessage `json:"upserts"`
|
|
Deletes map[string][]string `json:"deletes"`
|
|
}
|
|
|
|
// handleLibrarySync returns batched upserts + deletes since the supplied
|
|
// cursor. Cursor is the last `library_changes.id` the client has seen.
|
|
// Empty / zero / invalid cursor means "give me everything" (initial sync).
|
|
//
|
|
// Responses:
|
|
// - 204 No Content — no changes since cursor
|
|
// - 200 OK — JSON syncResponse with upserts, deletes, new cursor
|
|
// - 410 Gone — the client must reset its cursor to 0: the cursor is
|
|
// older than a delete the log has dropped, or past anything this server
|
|
// has handed out
|
|
// - 401 / 500 — standard envelope errors
|
|
func (h *handlers) handleLibrarySync(w http.ResponseWriter, r *http.Request) {
|
|
if _, ok := requireUser(w, r); !ok {
|
|
return
|
|
}
|
|
ctx := r.Context()
|
|
|
|
since, err := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
|
|
if err != nil || since < 0 {
|
|
since = 0
|
|
}
|
|
|
|
q := dbq.New(h.pool)
|
|
|
|
// The log keeps every entity's latest change, so a client syncing from
|
|
// 0 gets the whole library. It drops deletes older than its retention,
|
|
// and a cursor below the newest dropped one may have missed it: the
|
|
// client resets and syncs again from 0.
|
|
if since > 0 {
|
|
trimmed, err := q.GetLibraryChangesTrimmedThrough(ctx)
|
|
if err != nil {
|
|
writeErrWithLog(w, h.logger, "library_sync: GetLibraryChangesTrimmedThrough", err)
|
|
return
|
|
}
|
|
if since < trimmed {
|
|
writeErr(w, &apierror.Error{
|
|
Status: http.StatusGone,
|
|
Code: "cursor_too_old",
|
|
Message: "reset client cursor to 0 and resync",
|
|
})
|
|
return
|
|
}
|
|
// A cursor past anything this server has handed out comes from a
|
|
// server restored from an older backup: the changes between the
|
|
// backup and the cursor are gone, and the ones made from here on would
|
|
// reuse those ids. The app resets the same way.
|
|
lastCursor, err := q.GetLastIssuedLibraryChangeCursor(ctx)
|
|
if err != nil {
|
|
writeErrWithLog(w, h.logger, "library_sync: GetLastIssuedLibraryChangeCursor", err)
|
|
return
|
|
}
|
|
if since > lastCursor {
|
|
writeErr(w, &apierror.Error{
|
|
Status: http.StatusGone,
|
|
Code: "cursor_ahead",
|
|
Message: "this server holds no changes up to that cursor; reset client cursor to 0 and resync",
|
|
})
|
|
return
|
|
}
|
|
}
|
|
|
|
changes, err := q.GetLibraryChangesSince(ctx, dbq.GetLibraryChangesSinceParams{
|
|
ID: since,
|
|
Limit: SyncBatchLimit,
|
|
})
|
|
if err != nil {
|
|
writeErrWithLog(w, h.logger, "library_sync: GetLibraryChangesSince", err)
|
|
return
|
|
}
|
|
|
|
if len(changes) == 0 {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
|
|
// Group ids by entity type so we can fetch upsert payloads in batches.
|
|
upsertIDs := map[syncpkg.EntityType][]string{}
|
|
deleteIDs := map[syncpkg.EntityType][]string{}
|
|
var maxID int64
|
|
for _, c := range changes {
|
|
et := syncpkg.EntityType(c.EntityType)
|
|
if c.ID > maxID {
|
|
maxID = c.ID
|
|
}
|
|
if c.Op == string(syncpkg.OpUpsert) {
|
|
upsertIDs[et] = append(upsertIDs[et], c.EntityID)
|
|
} else {
|
|
deleteIDs[et] = append(deleteIDs[et], c.EntityID)
|
|
}
|
|
}
|
|
|
|
upserts, err := h.hydrateUpserts(ctx, q, upsertIDs)
|
|
if err != nil {
|
|
writeErrWithLog(w, h.logger, "library_sync: hydrateUpserts", err)
|
|
return
|
|
}
|
|
|
|
// Format deletes — convert EntityType keys to strings for JSON.
|
|
deletes := make(map[string][]string, len(deleteIDs))
|
|
for et, ids := range deleteIDs {
|
|
deletes[string(et)] = ids
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, syncResponse{
|
|
Cursor: maxID,
|
|
Upserts: upserts,
|
|
Deletes: deletes,
|
|
})
|
|
}
|
|
|
|
// hydrateUpserts loads the current row payloads for each upserted id,
|
|
// keyed by entity type (string form). The log covers the shared library
|
|
// only (artists, albums, tracks), so every caller sees the same rows.
|
|
func (h *handlers) hydrateUpserts(
|
|
ctx context.Context,
|
|
q *dbq.Queries,
|
|
ids map[syncpkg.EntityType][]string,
|
|
) (map[string][]json.RawMessage, error) {
|
|
out := map[string][]json.RawMessage{}
|
|
|
|
if rows := ids[syncpkg.EntityArtist]; len(rows) > 0 {
|
|
uuids := stringsToUUIDs(rows)
|
|
artists, err := q.GetArtistsByIDs(ctx, uuids)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, a := range artists {
|
|
b, _ := json.Marshal(toArtistSyncView(a))
|
|
out["artist"] = append(out["artist"], b)
|
|
}
|
|
}
|
|
if rows := ids[syncpkg.EntityAlbum]; len(rows) > 0 {
|
|
uuids := stringsToUUIDs(rows)
|
|
albums, err := q.GetAlbumsByIDs(ctx, uuids)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
gains, err := library.ReplayGainForAlbums(ctx, q, uuids)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, a := range albums {
|
|
b, _ := json.Marshal(toAlbumSyncView(a, gains[a.ID]))
|
|
out["album"] = append(out["album"], b)
|
|
}
|
|
}
|
|
if rows := ids[syncpkg.EntityTrack]; len(rows) > 0 {
|
|
uuids := stringsToUUIDs(rows)
|
|
tracks, err := q.GetTracksByIDs(ctx, uuids)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
gains, err := library.ReplayGainForTracks(ctx, q, uuids)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, t := range tracks {
|
|
b, _ := json.Marshal(toTrackSyncView(t, gains[t.ID]))
|
|
out["track"] = append(out["track"], b)
|
|
}
|
|
}
|
|
|
|
return out, nil
|
|
}
|
|
|
|
// stringsToUUIDs parses each string as a pgtype.UUID. Invalid entries
|
|
// are skipped silently — they can't have come from a valid scan/mutation.
|
|
func stringsToUUIDs(strs []string) []pgtype.UUID {
|
|
out := make([]pgtype.UUID, 0, len(strs))
|
|
for _, s := range strs {
|
|
u, ok := parseUUID(s)
|
|
if !ok {
|
|
continue
|
|
}
|
|
out = append(out, u)
|
|
}
|
|
return out
|
|
}
|