diff --git a/internal/api/main_test.go b/internal/api/main_test.go new file mode 100644 index 00000000..69ebe917 --- /dev/null +++ b/internal/api/main_test.go @@ -0,0 +1,23 @@ +package api + +import ( + "fmt" + "os" + "testing" + + "golang.org/x/crypto/bcrypt" +) + +// The tests hash passwords at bcrypt's lowest cost: what they check is which +// password is stored and who is signed out, not how slow a guess is. The +// cost the server uses is checked first, so lowering it here can't hide a +// weaker one there. +func TestMain(m *testing.M) { + if passwordCost < bcrypt.DefaultCost { + fmt.Fprintf(os.Stderr, "passwordCost is %d; stored passwords need at least bcrypt.DefaultCost (%d)\n", + passwordCost, bcrypt.DefaultCost) + os.Exit(1) + } + passwordCost = bcrypt.MinCost + os.Exit(m.Run()) +} diff --git a/internal/api/prelude.go b/internal/api/prelude.go index e0279373..6097d2f4 100644 --- a/internal/api/prelude.go +++ b/internal/api/prelude.go @@ -43,9 +43,14 @@ func checkNewPassword(w http.ResponseWriter, pw string) bool { return true } +// passwordCost is bcrypt's work factor for stored passwords. The package's +// tests lower it, since each hash at the default cost takes most of a second +// under the race detector; their TestMain refuses a default below bcrypt's. +var passwordCost = bcrypt.DefaultCost + // hashPassword is the one place a password is hashed for storage. func hashPassword(pw string) ([]byte, error) { - return bcrypt.GenerateFromPassword([]byte(pw), bcrypt.DefaultCost) + return bcrypt.GenerateFromPassword([]byte(pw), passwordCost) } // requireURLUUID parses the chi URL parameter named key as a UUID. On diff --git a/internal/genretag/genretag.go b/internal/genretag/genretag.go new file mode 100644 index 00000000..d53ca163 --- /dev/null +++ b/internal/genretag/genretag.go @@ -0,0 +1,23 @@ +// Package genretag reads a track's stored genre, one string that can name +// several genres. +package genretag + +import "strings" + +// Split returns the genres a track's genre string names. Tag editors join +// several genres with ";" or ","; each piece is trimmed and empty pieces are +// dropped, so a nil or blank genre gives none. A genre without either +// separator comes back whole. +func Split(genre *string) []string { + if genre == nil { + return nil + } + parts := strings.FieldsFunc(*genre, func(r rune) bool { return r == ';' || r == ',' }) + out := make([]string, 0, len(parts)) + for _, p := range parts { + if p = strings.TrimSpace(p); p != "" { + out = append(out, p) + } + } + return out +} diff --git a/internal/genretag/genretag_test.go b/internal/genretag/genretag_test.go new file mode 100644 index 00000000..1938dd7f --- /dev/null +++ b/internal/genretag/genretag_test.go @@ -0,0 +1,27 @@ +package genretag + +import ( + "slices" + "testing" +) + +func TestSplit(t *testing.T) { + for _, tc := range []struct { + in *string + want []string + }{ + {nil, nil}, + {ptr(""), nil}, + {ptr("Pop"), []string{"Pop"}}, + {ptr("Pop; Rock, Jazz"), []string{"Pop", "Rock", "Jazz"}}, + {ptr(" Pop ; Rock "), []string{"Pop", "Rock"}}, + {ptr(";; Pop ;;"), []string{"Pop"}}, + {ptr("Jazz Fusion"), []string{"Jazz Fusion"}}, + } { + if got := Split(tc.in); len(got)+len(tc.want) > 0 && !slices.Equal(got, tc.want) { + t.Errorf("Split(%v) = %q, want %q", tc.in, got, tc.want) + } + } +} + +func ptr(s string) *string { return &s } diff --git a/internal/recommendation/sessionvector.go b/internal/recommendation/sessionvector.go index f0e0f626..e2e7e6d6 100644 --- a/internal/recommendation/sessionvector.go +++ b/internal/recommendation/sessionvector.go @@ -1,11 +1,10 @@ package recommendation import ( - "strings" - "github.com/jackc/pgx/v5/pgtype" "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/genretag" ) type SessionVector struct { @@ -34,10 +33,8 @@ func BuildSessionVector(priorTracks []dbq.Track) SessionVector { seen[artistID] = true v.Artists = append(v.Artists, artistID) } - if t.Genre != nil && *t.Genre != "" { - for _, g := range splitGenres(*t.Genre) { - v.Tags[g]++ - } + for _, g := range genretag.Split(t.Genre) { + v.Tags[g]++ } v.RecentTrackIDs = append(v.RecentTrackIDs, uuidString(t.ID)) } @@ -50,20 +47,3 @@ func uuidString(u pgtype.UUID) string { } return u.String() } - -// splitGenres splits a track's denormalized genre string on the common -// multi-genre delimiters (`;`, `,`) used by various tag editors. Trims -// whitespace; drops empty fragments. Strings with no delimiter come back -// as a single-element slice. -func splitGenres(s string) []string { - parts := strings.FieldsFunc(s, func(r rune) bool { - return r == ';' || r == ',' - }) - out := make([]string, 0, len(parts)) - for _, p := range parts { - if p = strings.TrimSpace(p); p != "" { - out = append(out, p) - } - } - return out -} diff --git a/internal/recommendation/sessionvector_test.go b/internal/recommendation/sessionvector_test.go index b2f91bc3..da84f80b 100644 --- a/internal/recommendation/sessionvector_test.go +++ b/internal/recommendation/sessionvector_test.go @@ -135,40 +135,6 @@ func TestBuildSessionVector_NoSeparatorStaysOpaque(t *testing.T) { } } -func TestSplitGenres(t *testing.T) { - cases := []struct { - in string - want []string - }{ - {"", nil}, - {"Pop", []string{"Pop"}}, - {"Pop; Rock", []string{"Pop", "Rock"}}, - {"Pop, Rock", []string{"Pop", "Rock"}}, - {"Pop; Rock, Jazz", []string{"Pop", "Rock", "Jazz"}}, - {" Pop ; Rock ", []string{"Pop", "Rock"}}, - {";; Pop ;;", []string{"Pop"}}, - {"ElectronicComplextroGlitch Hop", []string{"ElectronicComplextroGlitch Hop"}}, - } - for _, c := range cases { - got := splitGenres(c.in) - if c.want == nil { - if len(got) != 0 { - t.Errorf("splitGenres(%q) = %v, want empty", c.in, got) - } - continue - } - if len(got) != len(c.want) { - t.Errorf("splitGenres(%q) = %v, want %v", c.in, got, c.want) - continue - } - for i := range got { - if got[i] != c.want[i] { - t.Errorf("splitGenres(%q)[%d] = %q, want %q", c.in, i, got[i], c.want[i]) - } - } - } -} - func TestBuildSessionVector_JSONRoundTrip(t *testing.T) { a1 := uuid("11111111-1111-1111-1111-111111111111") v := BuildSessionVector([]dbq.Track{ diff --git a/internal/recommendation/taste.go b/internal/recommendation/taste.go index 3d055241..19c8ce14 100644 --- a/internal/recommendation/taste.go +++ b/internal/recommendation/taste.go @@ -8,6 +8,7 @@ import ( "github.com/jackc/pgx/v5/pgtype" "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/genretag" ) // Taste-match tuning. The taste profile (written by internal/taste) holds @@ -105,7 +106,7 @@ func (p TasteProfile) Match( var tg float64 if genre != nil { - tags := splitGenres(*genre) + tags := genretag.Split(genre) if len(tags) > 0 { var sum float64 for _, t := range tags { diff --git a/internal/subsonic/mixes.go b/internal/subsonic/mixes.go index 1a5ab829..8d8b4961 100644 --- a/internal/subsonic/mixes.go +++ b/internal/subsonic/mixes.go @@ -13,6 +13,7 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/genretag" "github.com/Fabled-Sword/minstrel/internal/playlists" "github.com/Fabled-Sword/minstrel/internal/recommendation" ) @@ -341,11 +342,8 @@ func randomSongsFilter(ctx context.Context, q *dbq.Queries, genre, fromYear, toY } func hasGenre(tagged *string, genre string) bool { - if tagged == nil { - return false - } - for _, g := range strings.FieldsFunc(*tagged, func(r rune) bool { return r == ';' || r == ',' }) { - if strings.EqualFold(strings.TrimSpace(g), genre) { + for _, g := range genretag.Split(tagged) { + if strings.EqualFold(g, genre) { return true } } diff --git a/internal/taste/profile.go b/internal/taste/profile.go index 425e4bf1..9a9443cd 100644 --- a/internal/taste/profile.go +++ b/internal/taste/profile.go @@ -10,12 +10,12 @@ import ( "fmt" "log/slog" "sort" - "strings" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" "github.com/Fabled-Sword/minstrel/internal/db/dbq" + "github.com/Fabled-Sword/minstrel/internal/genretag" "github.com/Fabled-Sword/minstrel/internal/mood" ) @@ -185,7 +185,7 @@ func accumulate( for _, p := range plays { e := Engagement(p.Completion, cfg.Engagement) * decay(p.AgeDays, cfg.HalfLifeDays) artistW[p.ArtistID] += e - for _, tag := range splitGenres(p.Genre) { + for _, tag := range genretag.Split(p.Genre) { tagW[tag] += e } foldEnrichedTags(tagW, playedTags[p.TrackID], e, cfg.EnrichedTagScale) @@ -204,7 +204,7 @@ func accumulate( likedTags := groupTagsByTrack(likedTagRows) for _, lt := range likedTracks { artistW[lt.ArtistID] += cfg.TrackLikeBonus - for _, tag := range splitGenres(lt.Genre) { + for _, tag := range genretag.Split(lt.Genre) { tagW[tag] += cfg.TagLikeBonus } foldEnrichedTags(tagW, likedTags[lt.TrackID], cfg.TagLikeBonus, cfg.EnrichedTagScale) @@ -400,22 +400,3 @@ func uuidString(u pgtype.UUID) string { return fmt.Sprintf("%x-%x-%x-%x-%x", u.Bytes[0:4], u.Bytes[4:6], u.Bytes[6:8], u.Bytes[8:10], u.Bytes[10:16]) } - -// splitGenres splits a track's denormalized genre string on the common -// multi-genre delimiters, trimming whitespace and dropping empties. Mirrors -// the recommendation package's splitter (kept local to avoid a dependency). -func splitGenres(genre *string) []string { - if genre == nil || *genre == "" { - return nil - } - parts := strings.FieldsFunc(*genre, func(r rune) bool { - return r == ';' || r == ',' - }) - out := make([]string, 0, len(parts)) - for _, p := range parts { - if p = strings.TrimSpace(p); p != "" { - out = append(out, p) - } - } - return out -} diff --git a/internal/taste/profile_test.go b/internal/taste/profile_test.go index a0715a75..9b0e0580 100644 --- a/internal/taste/profile_test.go +++ b/internal/taste/profile_test.go @@ -88,32 +88,6 @@ func TestApplyFloor_ClampsNegatives(t *testing.T) { } } -func TestSplitGenres(t *testing.T) { - mk := func(s string) *string { return &s } - cases := []struct { - in *string - want []string - }{ - {nil, nil}, - {mk(""), nil}, - {mk("Rock"), []string{"Rock"}}, - {mk(" Rock "), []string{"Rock"}}, - {mk("Rock; Pop, Jazz"), []string{"Rock", "Pop", "Jazz"}}, - } - for _, c := range cases { - got := splitGenres(c.in) - if len(got) != len(c.want) { - t.Errorf("splitGenres(%v) len = %d, want %d", c.in, len(got), len(c.want)) - continue - } - for i := range got { - if got[i] != c.want[i] { - t.Errorf("splitGenres(%v)[%d] = %q, want %q", c.in, i, got[i], c.want[i]) - } - } - } -} - func TestUuidLess_Orders(t *testing.T) { a := pgtype.UUID{Bytes: [16]byte{1}, Valid: true} b := pgtype.UUID{Bytes: [16]byte{2}, Valid: true}