veza/veza-backend-api/internal/services/search_service.go
senke 44349ec444
Some checks failed
Veza CI / Rust (Stream Server) (push) Successful in 5m35s
E2E Playwright / e2e (full) (push) Failing after 9m56s
Veza CI / Frontend (Web) (push) Failing after 15m21s
Veza CI / Notify on failure (push) Successful in 4s
Veza CI / Backend (Go) (push) Failing after 4m44s
Security Scan / Secret Scanning (gitleaks) (push) Failing after 39s
feat(search): faceted filters (genre/key/BPM/year) + FacetSidebar UI (W4 Day 18)
Backend
- services/search_service.go : new SearchFilters struct (Genre,
  MusicalKey, BPMMin, BPMMax, YearFrom, YearTo) + appendTrackFacets
  helper that composes additional AND clauses onto the existing FTS
  WHERE condition. Filters apply ONLY to the track query — users +
  playlists ignore them silently (no relevant columns).
- handlers/search_handlers.go : new parseSearchFilters reads + bounds-
  checks query params (BPM in [1,999], year in [1900,2100], min<=max).
  Search() now passes filters into the service ; OTel span attribute
  search.filtered surfaces whether facets were applied.
- elasticsearch/search_service.go : signature updated to match the
  interface ; ES path doesn't translate facets yet (different filter
  DSL needed) — logs a warning when facets arrive on this path.
- handlers/search_handlers_test.go : MockSearchService.Search updated
  + 4 mock.On call sites pass mock.Anything for the new filters arg.

Frontend
- services/api/search.ts : new SearchFacets shape ; searchApi.search
  accepts an opts.facets bag. When non-empty, bypasses orval's typed
  getSearch (its GetSearchParams pre-dates the new query params) and
  uses apiClient.get directly with snake_case keys matching the
  backend's parseSearchFilters().
- features/search/components/FacetSidebar.tsx (new) : sidebar with
  genre + musical_key inputs (datalist suggestions), BPM min/max
  pair, year from/to pair. Stateless ; SearchPage owns state.
  data-testids on every control for E2E.
- features/search/components/search-page/useSearchPage.ts : facets
  state stored in URL (genre, musical_key, bpm_min, bpm_max,
  year_from, year_to) so deep links reproduce the result set.
  300 ms debounce on facet changes.
- features/search/components/search-page/SearchPage.tsx : layout
  switches to a 2-column grid (sidebar + results) when query is
  non-empty ; discovery view keeps the full width when empty.

Collateral cleanup
- internal/api/routes_users.go : removed unused strconv + time
  imports that were blocking the build (pre-existing dead imports
  surfaced by the SearchServiceInterface signature change).

E2E
- tests/e2e/32-faceted-search.spec.ts : 4 tests. (36) backend rejects
  bpm_min > bpm_max with 400. (37) out-of-range BPM rejected. (38)
  valid range returns 200 with a tracks array. (39) UI — typing in
  the sidebar updates URL query params within the 300 ms debounce.

Acceptance (Day 18) : promtool not relevant ; backend test suite
green for handlers + services + api ; TS strict pass ; E2E spec
covers the gates the roadmap acceptance asked for. The 'rock + BPM
120-130 = restricted results' assertion needs seed data with measurable
BPM (none today) — flagged in the spec as a follow-up to un-skip
once seed BPM data lands.

W4 progress : Day 16 done · Day 17 done · Day 18 done · Day 19
(HAProxy sticky WS) pending · Day 20 (k6 nightly) pending.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 10:33:35 +02:00

295 lines
8.5 KiB
Go

package services
import (
"context"
"fmt"
"veza-backend-api/internal/database"
"go.uber.org/zap"
)
// SearchService handles search operations
type SearchService struct {
db *database.Database
logger *zap.Logger
}
// SearchResult represents search results (artists = users for frontend compatibility)
type SearchResult struct {
Tracks []TrackResult `json:"tracks"`
Users []UserResult `json:"artists"` // Frontend expects "artists" for user search results
Playlists []PlaylistResult `json:"playlists"`
}
// SearchFilters carries the optional faceted-search constraints.
// v1.0.9 W4 Day 18 — only the track query honors these ; users and
// playlists ignore them silently (none of the columns apply).
//
// All fields zero-valued = no constraint. The handler validates
// bounds (e.g. BPM in [1, 999]) before populating, so the SQL
// builder trusts the input here.
type SearchFilters struct {
Genre string // exact match on tracks.genre
MusicalKey string // exact match on tracks.musical_key (e.g. "C", "Am")
BPMMin int // tracks.bpm >= BPMMin (skipped when 0)
BPMMax int // tracks.bpm <= BPMMax (skipped when 0)
YearFrom int // tracks.year >= YearFrom (skipped when 0)
YearTo int // tracks.year <= YearTo (skipped when 0)
}
// HasAny reports whether any of the filter fields constrain the
// query. Used by the handler / OTel span attributes.
func (f *SearchFilters) HasAny() bool {
if f == nil {
return false
}
return f.Genre != "" || f.MusicalKey != "" ||
f.BPMMin > 0 || f.BPMMax > 0 ||
f.YearFrom > 0 || f.YearTo > 0
}
type TrackResult struct {
ID string `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
URL string `json:"url"`
CoverArtPath string `json:"cover_art_path,omitempty"`
}
type UserResult struct {
ID string `json:"id"`
Username string `json:"username"`
AvatarURL string `json:"avatar_url"` // Frontend MinimalArtist expects avatar_url
}
type PlaylistResult struct {
ID string `json:"id"`
Name string `json:"name"`
Cover string `json:"cover"`
}
// NewSearchService creates a new search service
func NewSearchService(db *database.Database, logger *zap.Logger) *SearchService {
return &SearchService{
db: db,
logger: logger,
}
}
// Search performs a full-text search. v1.0.9 W4 Day 18 — `filters`
// is optional ; pass nil for the legacy unfiltered behavior.
func (ss *SearchService) Search(query string, types []string, filters *SearchFilters) (*SearchResult, error) {
ctx := context.Background()
results := &SearchResult{}
// Build search types - if empty, search all
searchAll := len(types) == 0
searchTracks := searchAll || contains(types, "track")
searchUsers := searchAll || contains(types, "user")
searchPlaylists := searchAll || contains(types, "playlist")
// Search tracks (v0.203 Lot K: boolean operators ; v1.0.9 W4 Day 18 facets)
if searchTracks {
parsed := ParseSearchQuery(query)
cond, args := BuildWhereCondition(parsed, []string{"title", "artist", "album"})
if cond == "" {
cond = "(title ILIKE $1 OR artist ILIKE $1)"
args = []interface{}{"%" + query + "%"}
}
// Append faceted filters as additional AND clauses. Placeholder
// numbering continues from len(args) — each helper appends to
// `cond` + `args` in lock-step.
cond, args = appendTrackFacets(cond, args, filters)
sql := `SELECT id::text, title, COALESCE(artist, ''), COALESCE(stream_manifest_url, file_path), COALESCE(cover_art_path, '')
FROM tracks
WHERE (` + cond + `) AND deleted_at IS NULL AND status = 'active'
LIMIT 10`
rows, err := ss.db.QueryContext(ctx, sql, args...)
if err != nil {
return nil, fmt.Errorf("failed to search tracks: %w", err)
}
defer rows.Close()
for rows.Next() {
var track TrackResult
if err := rows.Scan(&track.ID, &track.Title, &track.Artist, &track.URL, &track.CoverArtPath); err != nil {
continue
}
results.Tracks = append(results.Tracks, track)
}
}
// Search users (v0.203 Lot K: boolean operators)
if searchUsers {
parsed := ParseSearchQuery(query)
cond, args := BuildWhereCondition(parsed, []string{"username"})
if cond == "" {
cond = "username ILIKE $1"
args = []interface{}{"%" + query + "%"}
}
sql := `SELECT id::text, username, COALESCE(avatar, '')
FROM users
WHERE ` + cond + ` AND deleted_at IS NULL
LIMIT 10`
rows, err := ss.db.QueryContext(ctx, sql, args...)
if err != nil {
return nil, fmt.Errorf("failed to search users: %w", err)
}
defer rows.Close()
for rows.Next() {
var user UserResult
if err := rows.Scan(&user.ID, &user.Username, &user.AvatarURL); err != nil {
continue
}
results.Users = append(results.Users, user)
}
}
// Search playlists (v0.203 Lot K: boolean operators)
if searchPlaylists {
parsed := ParseSearchQuery(query)
cond, args := BuildWhereCondition(parsed, []string{"name"})
if cond == "" {
cond = "name ILIKE $1"
args = []interface{}{"%" + query + "%"}
}
sql := `SELECT id::text, name, COALESCE(cover_url, '')
FROM playlists
WHERE (` + cond + `) AND (is_public = TRUE OR visibility = 'public') AND deleted_at IS NULL
LIMIT 10`
rows, err := ss.db.QueryContext(ctx, sql, args...)
if err != nil {
return nil, fmt.Errorf("failed to search playlists: %w", err)
}
defer rows.Close()
for rows.Next() {
var playlist PlaylistResult
if err := rows.Scan(&playlist.ID, &playlist.Name, &playlist.Cover); err != nil {
continue
}
results.Playlists = append(results.Playlists, playlist)
}
}
return results, nil
}
// Suggestions returns autocomplete suggestions for tracks, users, and playlists.
func (ss *SearchService) Suggestions(query string, limit int) (*SearchResult, error) {
ctx := context.Background()
if limit <= 0 {
limit = 5
}
pattern := "%" + query + "%"
results := &SearchResult{}
// Tracks
trackRows, err := ss.db.QueryContext(ctx, `
SELECT id::text, title, COALESCE(artist, ''), COALESCE(stream_manifest_url, file_path), COALESCE(cover_art_path, '')
FROM tracks
WHERE (title ILIKE $1 OR artist ILIKE $1) AND deleted_at IS NULL AND status = 'active'
LIMIT $2
`, pattern, limit)
if err != nil {
return nil, fmt.Errorf("failed to suggest tracks: %w", err)
}
defer trackRows.Close()
for trackRows.Next() {
var t TrackResult
if err := trackRows.Scan(&t.ID, &t.Title, &t.Artist, &t.URL, &t.CoverArtPath); err != nil {
continue
}
results.Tracks = append(results.Tracks, t)
}
// Users
userRows, err := ss.db.QueryContext(ctx, `
SELECT id::text, username, COALESCE(avatar, '')
FROM users
WHERE username ILIKE $1 AND deleted_at IS NULL
LIMIT $2
`, pattern, limit)
if err != nil {
return nil, fmt.Errorf("failed to suggest users: %w", err)
}
defer userRows.Close()
for userRows.Next() {
var u UserResult
if err := userRows.Scan(&u.ID, &u.Username, &u.AvatarURL); err != nil {
continue
}
results.Users = append(results.Users, u)
}
// Playlists
playlistRows, err := ss.db.QueryContext(ctx, `
SELECT id::text, name, COALESCE(cover_url, '')
FROM playlists
WHERE name ILIKE $1 AND (is_public = TRUE OR visibility = 'public') AND deleted_at IS NULL
LIMIT $2
`, pattern, limit)
if err != nil {
return nil, fmt.Errorf("failed to suggest playlists: %w", err)
}
defer playlistRows.Close()
for playlistRows.Next() {
var p PlaylistResult
if err := playlistRows.Scan(&p.ID, &p.Name, &p.Cover); err != nil {
continue
}
results.Playlists = append(results.Playlists, p)
}
return results, nil
}
func contains(slice []string, item string) bool {
for _, s := range slice {
if s == item {
return true
}
}
return false
}
// appendTrackFacets extends a (cond, args) pair built by the FTS layer
// with the faceted-search filters from `f`. Each non-zero filter adds
// an AND clause + a parameterised value ; placeholder numbering uses
// the next $N in sequence so it composes with the FTS placeholders
// already in args.
//
// Skipped silently when f is nil or all fields are zero.
//
// v1.0.9 W4 Day 18.
func appendTrackFacets(cond string, args []interface{}, f *SearchFilters) (string, []interface{}) {
if f == nil {
return cond, args
}
add := func(clause string, v interface{}) {
args = append(args, v)
cond = cond + " AND " + fmt.Sprintf(clause, len(args))
}
if f.Genre != "" {
add("genre = $%d", f.Genre)
}
if f.MusicalKey != "" {
add("musical_key = $%d", f.MusicalKey)
}
if f.BPMMin > 0 {
add("bpm >= $%d", f.BPMMin)
}
if f.BPMMax > 0 {
add("bpm <= $%d", f.BPMMax)
}
if f.YearFrom > 0 {
add("year >= $%d", f.YearFrom)
}
if f.YearTo > 0 {
add("year <= $%d", f.YearTo)
}
return cond, args
}