diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b6df3439..fb5e7087 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -17,7 +17,7 @@ jobs: run: docker compose version - name: Build and run services - run: docker compose up -d db + run: docker compose up -d diff --git a/Makefile b/Makefile index 95d25ea2..25c0b3ff 100644 --- a/Makefile +++ b/Makefile @@ -6,19 +6,17 @@ test:: sqlc generate go test -count=1 -cover ./... -staging:: +esindexer-staging:: mkdir -p build/staging CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/staging/bridge-amd64 - rsync -ravz build/staging/ stage-discovery-4:bridgerton - ssh stage-discovery-4 -t 'cd bridgerton && docker compose up -d --build && docker compose restart bridge' - curl 'https://bridgerton.staging.audius.co' + rsync -ravz build/staging/ stage-elasticsearch:bridgerton + ssh stage-elasticsearch -t 'cd bridgerton && docker compose up -d --build && docker compose restart bridge' -production:: +esindexer-production:: mkdir -p build/production CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o build/production/bridge-amd64 - rsync -ravz build/production/ prod-discovery-4:bridgerton - ssh prod-discovery-4 -t 'cd bridgerton && docker compose up -d --build && docker compose restart bridge' - curl 'https://bridgerton.audius.co' + rsync -ravz build/production/ prod-elasticsearch:bridgerton + ssh prod-elasticsearch -t 'cd bridgerton && docker compose up -d --build && docker compose restart bridge' psql:: docker compose exec db psql -U postgres diff --git a/api/auth_middleware.go b/api/auth_middleware.go index c9ac348c..b72947ba 100644 --- a/api/auth_middleware.go +++ b/api/auth_middleware.go @@ -46,6 +46,12 @@ func (app *ApiServer) recoverAuthorityFromSignatureHeaders(c *fiber.Ctx) string // Checks if authedWallet is authorized to act on behalf of userId func (app *ApiServer) isAuthorizedRequest(ctx context.Context, userId int32, authedWallet string) bool { + + // tests can opt in to skipAuthCheck + if app.skipAuthCheck { + return true + } + cacheKey := fmt.Sprintf("%d:%s", userId, authedWallet) if hit, ok := app.resolveGrantCache.Get(cacheKey); ok { return hit diff --git a/api/fixture_test.go b/api/fixture_test.go index 1e554ff3..2ab5d562 100644 --- a/api/fixture_test.go +++ b/api/fixture_test.go @@ -12,6 +12,7 @@ import ( var ( baseRows = map[string]map[string]any{ "users": { + "blocknumber": 101, "user_id": nil, "handle": nil, "handle_lc": nil, @@ -29,6 +30,7 @@ var ( "profile_type": nil, }, "tracks": { + "blocknumber": 101, "blockhash": "block_abc123", "track_id": "@track_id", "is_current": true, @@ -54,8 +56,7 @@ var ( "download_conditions": nil, }, "playlists": { - // "playlist_id": 1, - // "playlist_owner_id": 42, + "blocknumber": 101, "is_album": false, "is_private": false, "playlist_contents": "{}", @@ -71,6 +72,8 @@ var ( "playlist_tracks": { "playlist_id": nil, "track_id": nil, + "created_at": time.Now(), + "updated_at": time.Now(), "is_removed": false, }, "follows": { diff --git a/api/searchv1/dsl_helpers.go b/api/searchv1/dsl_helpers.go new file mode 100644 index 00000000..9a7fe3e1 --- /dev/null +++ b/api/searchv1/dsl_helpers.go @@ -0,0 +1,89 @@ +package searchv1 + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strings" + + "github.com/elastic/go-elasticsearch/v8" + "github.com/elastic/go-elasticsearch/v8/esapi" + "github.com/tidwall/gjson" + "github.com/tidwall/pretty" +) + +func toAnySlice[T any](slice []T) []any { + result := make([]any, len(slice)) + for i, v := range slice { + result[i] = v + } + return result +} + +func BuildFunctionScoreDSL(scoreField string, innerQuery map[string]any) string { + innerJson, err := json.Marshal(innerQuery) + if err != nil { + panic(err) + } + + dsl := fmt.Sprintf(` + { + "query": { + "function_score": { + "query": %s, + "boost_mode": "multiply", + "score_mode": "multiply", + "functions": [ + { + "field_value_factor": { + "field": %q, + "factor": 100, + "modifier": "ln2p", + "missing": 0 + } + } + ] + } + } + }`, innerJson, scoreField) + + return dsl +} + +func SearchAndPluck(esClient *elasticsearch.Client, index, dsl string, limit, offset int) ([]int32, error) { + req := esapi.SearchRequest{ + Index: []string{index}, + Body: strings.NewReader(dsl), + Source: []string{"false"}, + Size: &limit, + From: &offset, + } + + res, err := req.Do(context.Background(), esClient) + if err != nil { + return nil, err + } + defer res.Body.Close() + + if res.IsError() { + return nil, fmt.Errorf("Search %s failed: %s", index, res.String()) + } + + body, err := io.ReadAll(res.Body) + if err != nil { + return nil, err + } + + result := []int32{} + for _, hit := range gjson.GetBytes(body, "hits.hits").Array() { + id := hit.Get("_id").Int() + result = append(result, int32(id)) + } + + return result, nil +} + +func pprintJson(j string) { + fmt.Println(string(pretty.Pretty([]byte(j)))) +} diff --git a/api/searchv1/playlist_search.go b/api/searchv1/playlist_search.go new file mode 100644 index 00000000..f131e934 --- /dev/null +++ b/api/searchv1/playlist_search.go @@ -0,0 +1,73 @@ +package searchv1 + +import ( + "fmt" + + "github.com/aquasecurity/esquery" +) + +type PlaylistSearchQuery struct { + Query string + Genres []string + Moods []string + IsTagSearch bool + IsAlbum bool + OnlyVerified bool + MyID int32 +} + +func (q *PlaylistSearchQuery) Map() map[string]any { + builder := esquery.Bool() + + if q.IsTagSearch { + builder.Must(esquery.MultiMatch().Query(q.Query).Fields("tracks.tags").Type(esquery.MatchTypeBoolPrefix)) + } else if q.Query != "" { + builder.Must(esquery.MultiMatch().Query(q.Query).Fields("title^10", "user.handle", "user.name", "tracks.tags").Type(esquery.MatchTypeBoolPrefix)) + } else { + builder.Must(esquery.MatchAll()) + } + + builder.Filter(esquery.Term("is_album", q.IsAlbum)) + + if len(q.Genres) > 0 { + builder.Filter(esquery.Terms("tracks.genre.keyword", toAnySlice(q.Genres)...)) + // by using a match query... the TF/IDF will apply to tracks. Which will rank playlists higher if they have a larger proportion of genre + for _, value := range q.Genres { + builder.Should(esquery.Match("tracks.genre", value)).Boost(10) + } + } + + if len(q.Moods) > 0 { + builder.Filter(esquery.Terms("tracks.mood.keyword", toAnySlice(q.Moods)...)) + // by using a match query... the TF/IDF will apply to tracks. Which will rank playlists higher if they have a larger proportion of mood + for _, value := range q.Genres { + builder.Should(esquery.Match("tracks.mood", value)).Boost(10) + } + } + + if q.OnlyVerified { + builder.Must(esquery.Term("tracks.user.is_verified", true)) + } else { + builder.Should(esquery.Term("user.is_verified", true)) + } + + // personalize results + if q.MyID > 0 { + builder.Should(esquery.CustomQuery(map[string]any{ + "terms": map[string]any{ + "_id": map[string]any{ + "index": "socials", + "id": fmt.Sprintf("%d", q.MyID), + "path": "reposted_playlist_ids", + }, + "boost": 10, + }, + })) + } + + return builder.Map() +} + +func (q *PlaylistSearchQuery) DSL() string { + return BuildFunctionScoreDSL("repost_count", q.Map()) +} diff --git a/api/searchv1/track_search.go b/api/searchv1/track_search.go new file mode 100644 index 00000000..6a2329e6 --- /dev/null +++ b/api/searchv1/track_search.go @@ -0,0 +1,109 @@ +package searchv1 + +import ( + "fmt" + + "github.com/aquasecurity/esquery" +) + +type TrackSearchQuery struct { + Query string + MinBPM int + MaxBPM int + IsDownloadable bool + IsPurchaseable bool + IsTagSearch bool + OnlyVerified bool + Genres []string + Moods []string + MusicalKeys []string + MyID int32 +} + +func (q *TrackSearchQuery) Map() map[string]any { + builder := esquery.Bool() + + if q.IsTagSearch { + builder.Must(esquery.MultiMatch().Query(q.Query).Fields("tags").Type(esquery.MatchTypeBoolPrefix)) + } else if q.Query != "" { + builder.Must( + esquery.MultiMatch(). + Query(q.Query). + Fields("title^10", "user.handle", "user.name", "tags"). + // Operator(esquery.OperatorAnd). + Type(esquery.MatchTypeBoolPrefix), + ) + + // for exact title / handle / artist name match + builder.Should( + esquery.MultiMatch().Query(q.Query).Fields("title", "user.name", "user.handle").Operator(esquery.OperatorAnd).Type(esquery.MatchTypePhrasePrefix), + ) + } else { + builder.Must(esquery.MatchAll()) + } + + if q.MinBPM > 0 || q.MaxBPM > 0 { + bpmRange := esquery.Range("bpm") + if q.MinBPM > 0 { + bpmRange.Gte(q.MinBPM) + } + if q.MaxBPM > 0 { + bpmRange.Lte(q.MaxBPM) + } + builder.Filter(bpmRange) + } + + if len(q.Genres) > 0 { + builder.Filter(esquery.Terms("genre.keyword", toAnySlice(q.Genres)...)) + } + + if len(q.Moods) > 0 { + builder.Filter(esquery.Terms("mood.keyword", toAnySlice(q.Moods)...)) + } + + if len(q.MusicalKeys) > 0 { + builder.Filter(esquery.Terms("musical_key.keyword", toAnySlice(q.MusicalKeys)...)) + } + + if q.IsDownloadable { + builder.Filter(esquery.Term("is_downloadable", true)) + } + + // todo: only_with_downloads + // => downloadable + has stems + + if q.IsPurchaseable { + // stream or download + builder.Filter( + esquery.Bool(). + Should(esquery.Exists("stream_conditions.usdc_purchase")). + Should(esquery.Exists("download_conditions.usdc_purchase")), + ) + } + + if q.OnlyVerified { + builder.Must(esquery.Term("user.is_verified", true)) + } else { + builder.Should(esquery.Term("user.is_verified", true)) + } + + // boost tracks that are saved / reposted + if q.MyID > 0 { + builder.Should(esquery.CustomQuery(map[string]any{ + "terms": map[string]any{ + "_id": map[string]any{ + "index": "socials", + "id": fmt.Sprintf("%d", q.MyID), + "path": "reposted_track_ids", + }, + "boost": 10, + }, + })) + } + + return builder.Map() +} + +func (q *TrackSearchQuery) DSL() string { + return BuildFunctionScoreDSL("repost_count", q.Map()) +} diff --git a/api/searchv1/user_search.go b/api/searchv1/user_search.go new file mode 100644 index 00000000..238472ab --- /dev/null +++ b/api/searchv1/user_search.go @@ -0,0 +1,67 @@ +package searchv1 + +import ( + "fmt" + + "github.com/aquasecurity/esquery" +) + +type UserSearchQuery struct { + Query string `json:"query"` + IsVerified bool `json:"is_verified"` + IsTagSearch bool + Genres []string + MyID int32 `json:"my_id"` +} + +func (q *UserSearchQuery) Map() map[string]any { + builder := esquery.Bool() + + if q.IsTagSearch { + builder.Must(esquery.MultiMatch().Query(q.Query).Fields("tracks.tags").Type(esquery.MatchTypeBoolPrefix)) + } else if q.Query != "" { + builder.Must(esquery.MultiMatch(q.Query).Fields("name", "handle").Type(esquery.MatchTypeBoolPrefix)) + + // for exact title match + builder.Should( + esquery.MultiMatch().Query(q.Query).Fields("name", "handle").Operator(esquery.OperatorAnd).Type(esquery.MatchTypePhrasePrefix), + ) + } else { + builder.Must(esquery.MatchAll()) + } + + if len(q.Genres) > 0 { + builder.Must(esquery.Range("track_count").Gt(0)) + builder.Filter(esquery.Terms("tracks.genre.keyword", toAnySlice(q.Genres)...)) + // by using a match query... the TF/IDF will apply to tracks. Which will rank profiles higher if they have a larger proportion of genre + for _, value := range q.Genres { + builder.Should(esquery.Match("tracks.genre", value)).Boost(10) + } + } + + if q.MyID > 0 { + builder.Should(esquery.CustomQuery(map[string]any{ + "terms": map[string]any{ + "_id": map[string]any{ + "index": "socials", + "id": fmt.Sprintf("%d", q.MyID), + "path": "following_user_ids", + }, + "boost": 10, + }, + })) + } + + if q.IsVerified { + builder.Must(esquery.Term("is_verified", true)) + } else { + builder.Should(esquery.Term("is_verified", true)) + } + + return builder.Map() +} + +func (q *UserSearchQuery) DSL() string { + inner := q.Map() + return BuildFunctionScoreDSL("follower_count", inner) +} diff --git a/api/server.go b/api/server.go index ff4154f2..3a8df7c8 100644 --- a/api/server.go +++ b/api/server.go @@ -15,12 +15,14 @@ import ( "bridgerton.audius.co/api/spl/programs/claimable_tokens" "bridgerton.audius.co/api/spl/programs/reward_manager" "bridgerton.audius.co/config" + "bridgerton.audius.co/esindexer" "bridgerton.audius.co/trashid" "github.com/AudiusProject/audiusd/pkg/rewards" "github.com/AudiusProject/audiusd/pkg/sdk" "github.com/Doist/unfurlist" adapter "github.com/axiomhq/axiom-go/adapters/zap" "github.com/axiomhq/axiom-go/axiom" + "github.com/elastic/go-elasticsearch/v8" "github.com/ethereum/go-ethereum/crypto" "github.com/gagliardetto/solana-go/rpc" "github.com/gofiber/contrib/fiberzap/v2" @@ -169,8 +171,15 @@ func NewApiServer(config config.Config) *ApiServer { panic(err) } + esClient, err := esindexer.Dial(config.EsUrl) + if err != nil { + panic(err) + } + auds := sdk.NewAudiusdSDK(config.AudiusdURL) + skipAuthCheck, _ := strconv.ParseBool(os.Getenv("skipAuthCheck")) + app := &ApiServer{ App: fiber.New(fiber.Config{ JSONEncoder: json.Marshal, @@ -179,9 +188,12 @@ func NewApiServer(config config.Config) *ApiServer { ReadBufferSize: 32_768, UnescapePath: true, }), + env: config.Env, + skipAuthCheck: skipAuthCheck, pool: pool, queries: dbv1.New(pool), logger: logger, + esClient: esClient, started: time.Now(), resolveHandleCache: &resolveHandleCache, resolveGrantCache: &resolveGrantCache, @@ -279,6 +291,7 @@ func NewApiServer(config config.Config) *ApiServer { for _, g := range []fiber.Router{v1, v1Full} { // Users g.Get("/users", app.v1Users) + g.Get("/users/search", app.v1UsersSearch) g.Get("/users/unclaimed_id", app.v1UsersUnclaimedId) g.Get("/users/top", app.v1UsersTop) g.Get("/users/genre/top", app.v1UsersGenreTop) @@ -328,6 +341,7 @@ func NewApiServer(config config.Config) *ApiServer { // Tracks g.Get("/tracks", app.v1Tracks) + g.Get("/tracks/search", app.v1TracksSearch) g.Get("/tracks/unclaimed_id", app.v1TracksUnclaimedId) g.Get("/tracks/trending", app.v1TracksTrending) @@ -355,6 +369,7 @@ func NewApiServer(config config.Config) *ApiServer { // Playlists g.Get("/playlists", app.v1Playlists) + g.Get("/playlists/search", app.v1PlaylistsSearch) g.Get("/playlists/unclaimed_id", app.v1PlaylistsUnclaimedId) g.Get("/playlists/trending", app.v1PlaylistsTrending) g.Get("/playlists/by_permalink/:handle/:slug", app.v1PlaylistByPermalink) @@ -367,6 +382,11 @@ func NewApiServer(config config.Config) *ApiServer { // Explore g.Get("/explore/best-selling", app.v1ExploreBestSelling) + // Search + g.Get("/search/autocomplete", app.v1SearchFull) + g.Get("/search/full", app.v1SearchFull) + g.Get("/search/tags", app.v1SearchFull) + // Developer Apps g.Get("/developer_apps/:address", app.v1DeveloperApps) @@ -452,6 +472,7 @@ type ApiServer struct { *fiber.App pool *pgxpool.Pool queries *dbv1.Queries + esClient *elasticsearch.Client logger *zap.Logger started time.Time resolveHandleCache *otter.Cache[string, int32] @@ -465,7 +486,9 @@ type ApiServer struct { solanaConfig *config.SolanaConfig antiAbuseOracles []string validators []config.Node + env string auds *sdk.AudiusdSDK + skipAuthCheck bool // set to true in a test if you don't care about auth middleware } func (app *ApiServer) home(c *fiber.Ctx) error { diff --git a/api/server_test.go b/api/server_test.go index 593a308a..127f0a66 100644 --- a/api/server_test.go +++ b/api/server_test.go @@ -60,6 +60,7 @@ func emptyTestApp(t *testing.T) *ApiServer { app := NewApiServer(config.Config{ Env: "test", ReadDbUrl: "postgres://postgres:example@localhost:21300/" + dbName, + EsUrl: "http://localhost:21400", DelegatePrivateKey: "0633fddb74e32b3cbc64382e405146319c11a1a52dc96598e557c5dbe2f31468", SolanaConfig: config.SolanaConfig{RpcProviders: []string{""}}, }) diff --git a/api/v1_playlists_search.go b/api/v1_playlists_search.go new file mode 100644 index 00000000..a24338be --- /dev/null +++ b/api/v1_playlists_search.go @@ -0,0 +1,16 @@ +package api + +import ( + "github.com/gofiber/fiber/v2" +) + +func (app *ApiServer) v1PlaylistsSearch(c *fiber.Ctx) error { + playlists, err := app.searchPlaylists(c) + if err != nil { + return err + } + + return c.JSON(fiber.Map{ + "data": playlists, + }) +} diff --git a/api/v1_search.go b/api/v1_search.go new file mode 100644 index 00000000..667b4fba --- /dev/null +++ b/api/v1_search.go @@ -0,0 +1,225 @@ +package api + +import ( + "strings" + + "bridgerton.audius.co/api/dbv1" + "bridgerton.audius.co/api/searchv1" + "github.com/gofiber/fiber/v2" + "golang.org/x/sync/errgroup" +) + +func (app *ApiServer) v1SearchFull(c *fiber.Ctx) error { + kind := c.Query("kind", "all") + + g := errgroup.Group{} + var users = []dbv1.FullUser{} + var tracks = []dbv1.FullTrack{} + var playlists = []dbv1.FullPlaylist{} + var albums = []dbv1.FullPlaylist{} + + // users + g.Go(func() (err error) { + if kind != "all" && kind != "users" { + return nil + } + + users, err = app.searchUsers(c) + return err + }) + + // tracks + g.Go(func() (err error) { + if kind != "all" && kind != "tracks" { + return nil + } + + tracks, err = app.searchTracks(c) + return err + }) + + // playlists + g.Go(func() (err error) { + if kind != "all" && kind != "playlists" { + return nil + } + + playlists, err = app.searchPlaylists(c) + return err + }) + + // albums + g.Go(func() (err error) { + if kind != "all" && kind != "albums" { + return nil + } + + albums, err = app.searchAlbums(c) + return err + }) + + err := g.Wait() + if err != nil { + return err + } + + return c.JSON(fiber.Map{ + "data": fiber.Map{ + "users": users, + "tracks": tracks, + "playlists": playlists, + "albums": albums, + + // todos + "saved_albums": []any{}, + "saved_users": []any{}, + "saved_tracks": []any{}, + "saved_playlists": []any{}, + }, + }) +} + +func (app *ApiServer) searchUsers(c *fiber.Ctx) ([]dbv1.FullUser, error) { + isTagSearch := strings.Contains(c.Route().Path, "search/tags") + isFullSearch := strings.Contains(c.Route().Path, "search/full") + limit := c.QueryInt("limit", 10) + offset := c.QueryInt("offset", 0) + myId := app.getMyId(c) + + q := searchv1.UserSearchQuery{ + Query: c.Query("query"), + IsVerified: c.QueryBool("is_verified"), + IsTagSearch: isTagSearch, + Genres: queryMutli(c, "genre"), + MyID: myId, + } + + userIds, err := searchv1.SearchAndPluck(app.esClient, "users", q.DSL(), limit, offset) + if err != nil { + return nil, err + } + + // savings: only personalize results for "full" endpoint + if !isFullSearch { + myId = 0 + } + + users, err := app.queries.FullUsers(c.Context(), dbv1.GetUsersParams{ + Ids: userIds, + MyID: myId, + }) + return users, err +} + +func (app *ApiServer) searchTracks(c *fiber.Ctx) ([]dbv1.FullTrack, error) { + isTagSearch := strings.Contains(c.Route().Path, "search/tags") + isFullSearch := strings.Contains(c.Route().Path, "search/full") + limit := c.QueryInt("limit", 10) + offset := c.QueryInt("offset", 0) + myId := app.getMyId(c) + + q := searchv1.TrackSearchQuery{ + MyID: myId, + IsTagSearch: isTagSearch, + Query: c.Query("query"), + Genres: queryMutli(c, "genre"), + Moods: queryMutli(c, "mood"), + MinBPM: c.QueryInt("bpm_min"), + MaxBPM: c.QueryInt("bpm_max"), + MusicalKeys: queryMutli(c, "key"), + IsDownloadable: c.QueryBool("is_downloadable"), + IsPurchaseable: c.QueryBool("is_purchaseable"), + OnlyVerified: c.QueryBool("only_verified"), + } + + tracksIds, err := searchv1.SearchAndPluck(app.esClient, "tracks", q.DSL(), limit, offset) + if err != nil { + return nil, err + } + + // savings: only personalize results for "full" endpoint + if !isFullSearch { + myId = 0 + } + + tracks, err := app.queries.FullTracks(c.Context(), dbv1.FullTracksParams{ + GetTracksParams: dbv1.GetTracksParams{ + Ids: tracksIds, + MyID: myId, + }, + }) + return tracks, err +} + +func (app *ApiServer) searchPlaylists(c *fiber.Ctx) ([]dbv1.FullPlaylist, error) { + isTagSearch := strings.Contains(c.Route().Path, "search/tags") + isFullSearch := strings.Contains(c.Route().Path, "search/full") + limit := c.QueryInt("limit", 10) + offset := c.QueryInt("offset", 0) + myId := app.getMyId(c) + + q := searchv1.PlaylistSearchQuery{ + MyID: myId, + IsTagSearch: isTagSearch, + Query: c.Query("query"), + Genres: queryMutli(c, "genre"), + Moods: queryMutli(c, "mood"), + OnlyVerified: c.QueryBool("only_verified"), + } + + playlistsIds, err := searchv1.SearchAndPluck(app.esClient, "playlists", q.DSL(), limit, offset) + if err != nil { + return nil, err + } + + // savings: only personalize results for "full" endpoint + if !isFullSearch { + myId = 0 + } + + playlists, err := app.queries.FullPlaylists(c.Context(), dbv1.FullPlaylistsParams{ + GetPlaylistsParams: dbv1.GetPlaylistsParams{ + Ids: playlistsIds, + MyID: myId, + }, + OmitTracks: true, + }) + return playlists, err +} + +func (app *ApiServer) searchAlbums(c *fiber.Ctx) ([]dbv1.FullPlaylist, error) { + isTagSearch := strings.Contains(c.Route().Path, "search/tags") + isFullSearch := strings.Contains(c.Route().Path, "search/full") + limit := c.QueryInt("limit", 10) + offset := c.QueryInt("offset", 0) + myId := app.getMyId(c) + + q := searchv1.PlaylistSearchQuery{ + MyID: myId, + IsTagSearch: isTagSearch, + Query: c.Query("query"), + Genres: queryMutli(c, "genre"), + Moods: queryMutli(c, "mood"), + OnlyVerified: c.QueryBool("only_verified"), + IsAlbum: true, + } + + playlistsIds, err := searchv1.SearchAndPluck(app.esClient, "playlists", q.DSL(), limit, offset) + if err != nil { + return nil, err + } + + // savings: only personalize results for "full" endpoint + if !isFullSearch { + myId = 0 + } + + playlists, err := app.queries.FullPlaylists(c.Context(), dbv1.FullPlaylistsParams{ + GetPlaylistsParams: dbv1.GetPlaylistsParams{ + Ids: playlistsIds, + MyID: myId, + }, + OmitTracks: true, + }) + return playlists, err +} diff --git a/api/v1_search_test.go b/api/v1_search_test.go new file mode 100644 index 00000000..1b1338c5 --- /dev/null +++ b/api/v1_search_test.go @@ -0,0 +1,376 @@ +package api + +import ( + "testing" + + "bridgerton.audius.co/esindexer" + "github.com/test-go/testify/require" +) + +func TestSearch(t *testing.T) { + app := emptyTestApp(t) + app.skipAuthCheck = true + + fixtures := FixtureMap{ + "users": { + { + "user_id": 1001, + "handle": "StereoSteve", + "name": "Stereo Steve", + }, + { + "user_id": 1002, + "handle": "StereoDave", + "name": "Stereo Dave", + }, + { + "user_id": 1003, + "handle": "monist", + "name": "Monist", + "is_verified": true, + }, + }, + "tracks": { + { + "track_id": 1001, + "owner_id": 1001, + "title": "peanut butter jam time", + "genre": "Trap", + "bpm": 88, + "mood": "Defiant", + "musical_key": "A minor", + }, + { + "track_id": 1002, + "owner_id": 1001, + "title": "mouse trap", + "genre": "Trap", + "bpm": 99, + "mood": "Uplifting", + "is_downloadable": true, + "musical_key": "B minor", + "tags": "Tag1,Tag2,Tag3", + }, + { + "track_id": 1003, + "owner_id": 1001, + "title": "sunny side", + "genre": "Jazz", + "mood": "Uplifting", + "stream_conditions": []byte(`{"usdc_purchase": {"price": 135, "splits": [{"user_id": 6, "percentage": 100.0}]}}`), + }, + { + "track_id": 1004, + "owner_id": 1001, + "title": "hide deleted", + "is_delete": true, + }, + { + "track_id": 1005, + "owner_id": 1001, + "title": "hide private", + "is_unlisted": true, + }, + { + "track_id": 1006, + "owner_id": 1001, + "title": "hide unavailable", + "is_available": false, + }, + { + "track_id": 1007, + "owner_id": 1003, + "title": "circular thoughts", + }, + }, + "playlists": { + { + "playlist_id": 9001, + "playlist_owner_id": 1001, + "playlist_name": "Old and Busted", + }, + { + "playlist_id": 9002, + "playlist_owner_id": 1001, + "playlist_name": "My Old Album", + "is_album": true, + }, + { + "playlist_id": 9003, + "playlist_owner_id": 1001, + "playlist_name": "Hot and New", + }, + }, + "playlist_tracks": { + { + "playlist_id": 9003, + "track_id": 1007, + }, + }, + "follows": { + {"follower_user_id": 1001, "followee_user_id": 1002}, + }, + "reposts": { + { + "repost_item_id": 1001, + "user_id": 1001, + "repost_type": "track", + "created_at": parseTime(t, "2024-01-03"), + }, + { + "repost_item_id": 1001, + "user_id": 1002, + "repost_type": "track", + "created_at": parseTime(t, "2024-01-03"), + }, + { + "repost_item_id": 1003, + "user_id": 1003, + "repost_type": "track", + "created_at": parseTime(t, "2024-01-03"), + }, + }, + } + + createFixtures(app, fixtures) + + // index data to ES + esindexer.Reindex(app.pool, app.esClient, true) + + // users: + { + status, body := testGet(t, app, "/v1/search/autocomplete?query=stereo") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.users.#": 2, + "data.users.0.handle": "StereoDave", + "data.users.1.handle": "StereoSteve", + }) + } + + // users: prefix match + { + status, body := testGet(t, app, "/v1/search/autocomplete?query=ster") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.users.#": 2, + "data.users.0.handle": "StereoDave", + "data.users.1.handle": "StereoSteve", + }) + } + + { + status, body := testGet(t, app, "/v1/users/search?query=stereo") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.#": 2, + "data.0.handle": "StereoDave", + "data.1.handle": "StereoSteve", + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?is_verified=true") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.users.#": 1, + "data.users.0.handle": "monist", + }) + } + + // tracks: default rank is by repost count + { + status, body := testGet(t, app, "/v1/search/autocomplete") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.0.title": "peanut butter jam time", + "data.tracks.0.repost_count": 2, + }) + } + + // but if you pass a user_id and have reposted a track... + // your history will rank it higher + { + status, body := testGet(t, app, "/v1/search/autocomplete?user_id=1003") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.0.title": "sunny side", + "data.tracks.0.repost_count": 1, + }) + } + + // tracks: filter by genre + mood + bpm + { + status, body := testGet(t, app, "/v1/search/autocomplete?genre=Trap") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 2, + }) + } + + // tracks: only verified + { + status, body := testGet(t, app, "/v1/search/autocomplete?only_verified=true") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.0.title": "circular thoughts", + }) + } + + // can search artist + track title + { + status, body := testGet(t, app, "/v1/search/autocomplete?query=stereo+sun") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 3, + "data.tracks.0.title": "sunny side", + }) + } + + // can search tags + { + status, body := testGet(t, app, "/v1/search/autocomplete?query=Tag2") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 1, + "data.tracks.0.title": "mouse trap", + }) + } + + // doesn't show deleted or unlisted tracks + { + status, body := testGet(t, app, "/v1/search/autocomplete?query=hide") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 0, + }) + } + + // can search artist handle + { + status, body := testGet(t, app, "/v1/search/autocomplete?query=stereosteve") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 3, + "data.tracks.0.user.handle": "StereoSteve", + }) + } + + // can search artist name + if false { + status, body := testGet(t, app, "/v1/search/autocomplete?query=stereo+steve") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 1, + "data.tracks.0.title": "sunny side", + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?genre=Trap&bpm_min=90") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 1, + "data.tracks.0.title": "mouse trap", + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?genre=Trap&bpm_max=90") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 1, + "data.tracks.0.title": "peanut butter jam time", + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?genre=Trap&genre=Jazz") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 3, + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?genre=Trap&genre=Jazz&mood=Uplifting") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 2, + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?is_downloadable=true") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 1, + "data.tracks.0.title": "mouse trap", + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?key=A+minor") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 1, + "data.tracks.0.title": "peanut butter jam time", + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?key=A+minor&key=B+minor") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 2, + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?is_purchaseable=true") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.tracks.#": 1, + "data.tracks.0.title": "sunny side", + }) + } + + // + // Playlists + // + + { + status, body := testGet(t, app, "/v1/search/autocomplete?query=old") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.playlists.#": 1, + "data.playlists.0.playlist_name": "Old and Busted", + "data.albums.#": 1, + "data.albums.0.playlist_name": "My Old Album", + }) + } + + { + status, body := testGet(t, app, "/v1/search/autocomplete?only_verified=true") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.playlists.0.playlist_name": "Hot and New", + }) + } + + // + // tag search + // + + // users: + { + status, body := testGet(t, app, "/v1/search/tags?query=Tag2") + require.Equal(t, 200, status) + jsonAssert(t, body, map[string]any{ + "data.users.#": 1, + "data.users.0.handle": "StereoSteve", + "data.tracks.#": 1, + "data.tracks.0.title": "mouse trap", + }) + } +} diff --git a/api/v1_tracks_search.go b/api/v1_tracks_search.go new file mode 100644 index 00000000..48b0daae --- /dev/null +++ b/api/v1_tracks_search.go @@ -0,0 +1,16 @@ +package api + +import ( + "github.com/gofiber/fiber/v2" +) + +func (app *ApiServer) v1TracksSearch(c *fiber.Ctx) error { + tracks, err := app.searchTracks(c) + if err != nil { + return err + } + + return c.JSON(fiber.Map{ + "data": tracks, + }) +} diff --git a/api/v1_users_search.go b/api/v1_users_search.go new file mode 100644 index 00000000..428bedd9 --- /dev/null +++ b/api/v1_users_search.go @@ -0,0 +1,16 @@ +package api + +import ( + "github.com/gofiber/fiber/v2" +) + +func (app *ApiServer) v1UsersSearch(c *fiber.Ctx) error { + users, err := app.searchUsers(c) + if err != nil { + return err + } + + return c.JSON(fiber.Map{ + "data": users, + }) +} diff --git a/compose.yml b/compose.yml index c28510c5..9da5fa67 100644 --- a/compose.yml +++ b/compose.yml @@ -28,3 +28,21 @@ services: # - "log_statement=all" - "-c" - "max_connections=1000" + + elasticsearch: + image: docker.elastic.co/elasticsearch/elasticsearch:8.10.2 + container_name: elasticsearch + environment: + - network.host=0.0.0.0 + - discovery.type=single-node + - cluster.name=docker-cluster + - node.name=cluster1-node1 + - xpack.license.self_generated.type=basic + - xpack.security.enabled=false + - "ES_JAVA_OPTS=-Xms512m -Xmx512m" + ulimits: + memlock: + soft: -1 + hard: -1 + ports: + - 21400:9200 diff --git a/config/config.go b/config/config.go index 8f635815..decf97de 100644 --- a/config/config.go +++ b/config/config.go @@ -13,6 +13,7 @@ type Config struct { Env string ReadDbUrl string WriteDbUrl string + EsUrl string Nodes []Node DeadNodes []string DelegatePrivateKey string @@ -30,6 +31,7 @@ var Cfg = Config{ Env: os.Getenv("ENV"), ReadDbUrl: os.Getenv("readDbUrl"), WriteDbUrl: os.Getenv("writeDbUrl"), + EsUrl: os.Getenv("elasticsearchUrl"), DelegatePrivateKey: os.Getenv("delegatePrivateKey"), AxiomToken: os.Getenv("axiomToken"), AxiomDataset: os.Getenv("axiomDataset"), diff --git a/esindexer/conn.go b/esindexer/conn.go new file mode 100644 index 00000000..e43bd98c --- /dev/null +++ b/esindexer/conn.go @@ -0,0 +1,13 @@ +package esindexer + +import "github.com/elastic/go-elasticsearch/v8" + +func Dial(esUrl string) (*elasticsearch.Client, error) { + cfg := elasticsearch.Config{ + Addresses: []string{ + esUrl, + }, + } + + return elasticsearch.NewClient(cfg) +} diff --git a/esindexer/esindexer.go b/esindexer/esindexer.go new file mode 100644 index 00000000..c35ae276 --- /dev/null +++ b/esindexer/esindexer.go @@ -0,0 +1,196 @@ +package esindexer + +import ( + "context" + "fmt" + "log" + "log/slog" + "strconv" + "strings" + + "github.com/elastic/go-elasticsearch/v8" + "github.com/elastic/go-elasticsearch/v8/esutil" + "github.com/jackc/pgx/v5/pgxpool" +) + +type collectionConfig struct { + indexName string + idColumn string + mapping string + sql string +} + +var collectionConfigs = map[string]collectionConfig{ + "users": userConfig, + "tracks": tracksConfig, + "playlists": playlistsConfig, + "socials": socialsConfig, +} + +type EsIndexer struct { + pool *pgxpool.Pool + esc *elasticsearch.Client + bulk esutil.BulkIndexer + drop bool +} + +func (indexer *EsIndexer) createIndex(collection string) error { + cc := collectionConfigs[collection] + + if indexer.drop { + _, err := indexer.esc.Indices.Delete([]string{cc.indexName}) + if err != nil { + fmt.Println("drop error", cc.indexName, err) + } + } + + res, err := indexer.esc.Indices.Create( + cc.indexName, + indexer.esc.Indices.Create.WithBody( + strings.NewReader(cc.mapping), + ), + ) + if err != nil { + fmt.Println("create index error", cc.indexName, err) + return err + } + + fmt.Println("created index", cc.indexName) + return res.Body.Close() +} + +func (indexer *EsIndexer) indexAll(collection string) error { + cc := collectionConfigs[collection] + + err := indexer.indexSql(cc.indexName, cc.sql) + if err != nil { + return err + } + + slog.Info("index all stats", "collection", collection, "stats", indexer.bulk.Stats()) + + return nil +} + +func (indexer *EsIndexer) indexIds(collection string, ids ...int64) error { + if len(ids) == 0 { + return nil + } + + cc := collectionConfigs[collection] + stringIds := make([]string, len(ids)) + for idx, id := range ids { + stringIds[idx] = strconv.Itoa(int(id)) + } + + sql := fmt.Sprintf("%s AND %s IN (%s)", + cc.sql, + cc.idColumn, + strings.Join(stringIds, ",")) + + slog.Info("index", "collection", collection, "ids", ids) + + return indexer.indexSql(cc.indexName, sql) +} + +func (indexer *EsIndexer) indexSql(indexName, sql string) error { + + ctx := context.Background() + + rows, err := indexer.pool.Query(ctx, sql) + if err != nil { + return err + } + defer rows.Close() + + for rows.Next() { + var id int + var doc string + if err := rows.Scan(&id, &doc); err != nil { + fmt.Println("row scan error:", err) + continue + } + + err = indexer.bulk.Add(ctx, esutil.BulkIndexerItem{ + Action: "index", + Index: indexName, + DocumentID: fmt.Sprintf("%d", id), + Body: strings.NewReader(doc), + OnSuccess: func(ctx context.Context, item esutil.BulkIndexerItem, res esutil.BulkIndexerResponseItem) {}, + OnFailure: func(ctx context.Context, item esutil.BulkIndexerItem, res esutil.BulkIndexerResponseItem, err error) { + if err != nil { + log.Printf("ERROR: %s", err) + } else { + log.Printf("ERROR: %s: %s", res.Error.Type, res.Error.Reason) + } + }, + }) + + if err != nil { + fmt.Println("es index error:", err) + continue + } + } + + return rows.Err() +} + +// this uses painless to 'patch' a `socials` doc to add / remove an entity ID from a list of ids. +// without forcing postgres to re-do the socials query from scratch. +// If missing (i.e. for a new user) it will fall back to re-doing from scratch. +// This might be a "too clever by half" type of thing... in which case, the listener could just use `indexIds` +// like the other collections +func (indexer *EsIndexer) scriptedUpdateSocial(userId int64, fieldName string, entityId int64, isDelete bool) { + painlessAddEntity := ` + def user = ctx._source; + if (!user[params.fieldName].contains(params.entityId)) { + user[params.fieldName].add(params.entityId); + } else { + ctx.op = 'noop' + } + ` + + painlessRemoveEntity := ` + def user = ctx._source; + def idx = user[params.fieldName].indexOf(params.entityId); + if (idx > -1) { + user[params.fieldName].remove(idx); + } else { + ctx.op = 'noop' + } + ` + + script := painlessAddEntity + if isDelete { + script = painlessRemoveEntity + } + + resp, err := indexer.esc.Update( + "socials", + fmt.Sprintf("%d", userId), + strings.NewReader(fmt.Sprintf(`{ + "script": { + "source": %q, + "lang": "painless", + "params": { + "fieldName": %q, + "entityId": %d + } + } + }`, script, fieldName, entityId)), + ) + defer resp.Body.Close() + + if err != nil { + log.Printf("scripted update error: %v", err) + } else if resp.StatusCode != 200 { + if err := indexer.indexIds("socials", userId); err != nil { + slog.Error("socials indexIds failed", "user", userId, "field", fieldName, "id", entityId, "err", err) + } else { + slog.Info("socials indexIds", "user", userId, "field", fieldName, "id", entityId) + } + } else { + slog.Info("social update", "user", userId, "field", fieldName, "id", entityId) + } + +} diff --git a/esindexer/esindexer_listen.go b/esindexer/esindexer_listen.go new file mode 100644 index 00000000..97b7e315 --- /dev/null +++ b/esindexer/esindexer_listen.go @@ -0,0 +1,153 @@ +package esindexer + +import ( + "context" + "fmt" + "log" + "slices" + "sync" + "time" + + "bridgerton.audius.co/config" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgxlisten" + "github.com/tidwall/gjson" + + _ "github.com/joho/godotenv/autoload" +) + +type pendingChanges struct { + sync.Mutex + idMap map[string][]int64 +} + +func (pending *pendingChanges) enqueue(collection string, id int64) { + pending.Lock() + defer pending.Unlock() + + if _, ok := pending.idMap[collection]; !ok { + pending.idMap[collection] = []int64{} + } + + if !slices.Contains(pending.idMap[collection], id) { + pending.idMap[collection] = append(pending.idMap[collection], id) + } +} + +func (pending *pendingChanges) take() map[string][]int64 { + pending.Lock() + defer pending.Unlock() + + idMap := pending.idMap + pending.idMap = map[string][]int64{} + return idMap +} + +func (indexer *EsIndexer) listen(ctx context.Context) error { + + listener := &pgxlisten.Listener{ + Connect: func(ctx context.Context) (*pgx.Conn, error) { + // Provide a pgx connection for listening + // LISTEN needs to use the write leader + return pgx.Connect(ctx, config.Cfg.WriteDbUrl) + }, + LogError: func(ctx context.Context, err error) { + log.Println("Listener error:", err) + }, + ReconnectDelay: 10 * time.Second, + } + + pending := &pendingChanges{ + idMap: map[string][]int64{}, + } + + // entity changes get batched up and processed every N seconds + userHandler := pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { + id := gjson.Get(notification.Payload, "user_id").Int() + pending.enqueue("users", id) + return nil + }) + + trackHandler := pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { + id := gjson.Get(notification.Payload, "track_id").Int() + pending.enqueue("tracks", id) + return nil + }) + + playlistHandler := pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { + id := gjson.Get(notification.Payload, "playlist_id").Int() + pending.enqueue("playlists", id) + return nil + }) + + listener.Handle("users", userHandler) + listener.Handle("aggregate_user", userHandler) + listener.Handle("tracks", trackHandler) + listener.Handle("aggregate_track", trackHandler) + listener.Handle("playlists", playlistHandler) + listener.Handle("playlist_track", playlistHandler) + + // "socials" changes do update via a painless script + listener.Handle("follows", pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { + followerId := gjson.Get(notification.Payload, "follower_user_id").Int() + followeeId := gjson.Get(notification.Payload, "followee_user_id").Int() + isDelete := gjson.Get(notification.Payload, "is_delete").Bool() + + indexer.scriptedUpdateSocial(followerId, "following_user_ids", followeeId, isDelete) + return nil + })) + + listener.Handle("reposts", pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { + userId := gjson.Get(notification.Payload, "user_id").Int() + isTrack := gjson.Get(notification.Payload, "repost_type").String() == "track" + id := gjson.Get(notification.Payload, "repost_item_id").Int() + isDelete := gjson.Get(notification.Payload, "is_delete").Bool() + + field := "reposted_playlist_ids" + if isTrack { + field = "reposted_track_ids" + } + + indexer.scriptedUpdateSocial(userId, field, id, isDelete) + return nil + })) + + listener.Handle("saves", pgxlisten.HandlerFunc(func(ctx context.Context, notification *pgconn.Notification, conn *pgx.Conn) error { + userId := gjson.Get(notification.Payload, "user_id").Int() + isTrack := gjson.Get(notification.Payload, "save_type").String() == "track" + id := gjson.Get(notification.Payload, "save_item_id").Int() + isDelete := gjson.Get(notification.Payload, "is_delete").Bool() + + field := "saved_playlist_ids" + if isTrack { + field = "saved_track_ids" + } + + indexer.scriptedUpdateSocial(userId, field, id, isDelete) + return nil + })) + + // this fires all the time... + // but we're not even indexing play_count atm... + // todo: index play count + // also... we might not need to update this so often... + // listener.Handle("aggregate_plays", logNotify) + + go func() { + ticker := time.NewTicker(10 * time.Second) + defer ticker.Stop() + for range ticker.C { + idMap := pending.take() + for collection, ids := range idMap { + if err := indexer.indexIds(collection, ids...); err != nil { + log.Printf("Error indexing %s: %v", collection, err) + } + } + } + }() + + fmt.Println("🚀 Starting listener...") + return listener.Listen(ctx) + +} diff --git a/esindexer/esindexer_listen_test.go b/esindexer/esindexer_listen_test.go new file mode 100644 index 00000000..372ca6cf --- /dev/null +++ b/esindexer/esindexer_listen_test.go @@ -0,0 +1,23 @@ +package esindexer + +import ( + "testing" + + "github.com/test-go/testify/require" +) + +func TestPending(t *testing.T) { + pending := &pendingChanges{ + idMap: map[string][]int64{}, + } + + pending.enqueue("users", 1) + pending.enqueue("users", 1) + pending.enqueue("users", 2) + pending.enqueue("tracks", 3) + + idMap := pending.take() + require.Equal(t, []int64{1, 2}, idMap["users"]) + require.Empty(t, pending.idMap["users"]) + +} diff --git a/esindexer/playlists_index.go b/esindexer/playlists_index.go new file mode 100644 index 00000000..4829b213 --- /dev/null +++ b/esindexer/playlists_index.go @@ -0,0 +1,59 @@ +package esindexer + +var playlistsConfig = collectionConfig{ + indexName: "playlists", + idColumn: "playlist_id", + sql: ` + SELECT + playlist_id, + json_build_object( + 'title', playlist_name, + 'description', description, + 'track_count', track_count, + 'save_count', aggregate_playlist.save_count, + 'repost_count', aggregate_playlist.repost_count, + 'created_at', playlists.created_at, + 'updated_at', playlists.updated_at, + 'blocknumber', playlists.blocknumber, + 'is_private', is_private, + 'is_album', playlists.is_album, + 'user', json_build_object( + 'handle', users.handle, + 'name', users.name, + 'location', users.location, + 'follower_count', aggregate_user.follower_count, + 'is_verified', is_verified + ), + 'tracks', ( + SELECT json_agg( + json_build_object( + 'title', title, + 'genre', genre, + 'mood', mood, + 'tags', string_to_array(tags, ','), + + -- todo: more track fields + 'user', json_build_object( + 'handle', users.handle, + 'name', users.name, + 'location', users.location, + 'follower_count', aggregate_user.follower_count, + 'is_verified', is_verified + ) + ) + ) + FROM playlist_tracks + JOIN tracks USING (track_id) + JOIN users ON owner_id = user_id + WHERE playlist_id = playlists.playlist_id + ) + ) + FROM playlists + JOIN aggregate_playlist USING (playlist_id) + JOIN users ON playlist_owner_id = user_id + JOIN aggregate_user USING (user_id) + WHERE is_private = false + AND users.is_available = true + AND users.is_deactivated = false + `, +} diff --git a/esindexer/reindex.go b/esindexer/reindex.go new file mode 100644 index 00000000..a19adfa3 --- /dev/null +++ b/esindexer/reindex.go @@ -0,0 +1,124 @@ +package esindexer + +import ( + "context" + "fmt" + "log" + "os" + "os/signal" + "slices" + "syscall" + + "bridgerton.audius.co/config" + "github.com/elastic/go-elasticsearch/v8" + "github.com/elastic/go-elasticsearch/v8/esutil" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/tidwall/sjson" +) + +func mustDialPostgres() *pgxpool.Pool { + connConfig, err := pgxpool.ParseConfig(config.Cfg.WriteDbUrl) + if err != nil { + panic(err) + } + + pool, err := pgxpool.NewWithConfig(context.Background(), connConfig) + if err != nil { + panic(err) + } + return pool +} + +func mustDialElasticsearch() *elasticsearch.Client { + esc, err := Dial(config.Cfg.EsUrl) + if err != nil { + log.Fatalf("Error creating the client: %s", err) + } + return esc +} + +func commonIndexSettings(mapping string) string { + mustSet := func(key string, value any) { + var err error + mapping, err = sjson.Set(mapping, key, value) + if err != nil { + panic(err) + } + } + + mustSet("settings.number_of_shards", 1) + mustSet("settings.number_of_replicas", 0) + return mapping +} + +func reindexCollection(i *EsIndexer, collection string) { + if err := i.createIndex(collection); err != nil { + panic(err) + } + if err := i.indexAll(collection); err != nil { + panic(err) + } +} + +func Reindex(pool *pgxpool.Pool, esc *elasticsearch.Client, drop bool, collections ...string) { + + bulk, err := esutil.NewBulkIndexer(esutil.BulkIndexerConfig{ + Client: esc, + NumWorkers: 2, + Refresh: "true", + }) + if err != nil { + log.Fatalf("Error creating the indexer: %s", err) + } + + esIndexer := &EsIndexer{ + pool, + esc, + bulk, + drop, + } + + // this is just a "listen" demo for now... + // this will block forever + // todo: need to figure out if this runs after any re-index, or concurrently... + if slices.Contains(collections, "listen") { + ctx, cancel := context.WithCancel(context.Background()) + + // Listen for Ctrl+C (SIGINT) and call cancel when received + sigCh := make(chan os.Signal, 1) + signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) + go func() { + <-sigCh + fmt.Println("Listen exit") + cancel() + os.Exit(0) + }() + + esIndexer.listen(ctx) + + } + + reindexAll := len(collections) == 0 || slices.Contains(collections, "all") + + if reindexAll || slices.Contains(collections, "playlists") { + reindexCollection(esIndexer, "playlists") + } + if reindexAll || slices.Contains(collections, "tracks") { + reindexCollection(esIndexer, "tracks") + } + if reindexAll || slices.Contains(collections, "users") { + reindexCollection(esIndexer, "users") + } + if reindexAll || slices.Contains(collections, "socials") { + reindexCollection(esIndexer, "socials") + } + + esIndexer.bulk.Close(context.Background()) + +} + +func ReindexLegacy(drop bool, collections ...string) { + pool := mustDialPostgres() + esc := mustDialElasticsearch() + Reindex(pool, esc, drop, collections...) +} diff --git a/esindexer/settings_test.go b/esindexer/settings_test.go new file mode 100644 index 00000000..bf457f43 --- /dev/null +++ b/esindexer/settings_test.go @@ -0,0 +1,50 @@ +package esindexer + +import ( + "testing" + + "bridgerton.audius.co/utils" +) + +func TestCommonIndexSettings(t *testing.T) { + { + mapping := `{ + "mappings": { + "properties": { + "name": { + "type": "text" + }, + "handle": { + "type": "text" + }, + "location": { + "type": "text" + }, + "follower_count": { + "type": "integer" + }, + "track_count": { + "type": "integer" + } + } + } + }` + + m2 := commonIndexSettings(mapping) + + utils.JsonAssert(t, []byte(m2), map[string]any{ + "mappings.properties.name.type": "text", + "settings.number_of_shards": 1, + "settings.number_of_replicas": 0, + }) + } + + // works with empty mapping + { + m2 := commonIndexSettings(``) + utils.JsonAssert(t, []byte(m2), map[string]any{ + "settings.number_of_shards": 1, + "settings.number_of_replicas": 0, + }) + } +} diff --git a/esindexer/socials_index.go b/esindexer/socials_index.go new file mode 100644 index 00000000..7fc32225 --- /dev/null +++ b/esindexer/socials_index.go @@ -0,0 +1,84 @@ +package esindexer + +// user id => list of following, repost (tracks), save (tracks), repost (playlists), repost (playlist) + +var socialsConfig = collectionConfig{ + indexName: "socials", + idColumn: "user_id", + mapping: ` + { + "mappings": { + "properties": { + "saved_track_ids": { "type": "keyword" }, + "reposted_track_ids": { "type": "keyword" }, + "saved_playlist_ids": { "type": "keyword" }, + "reposted_playlist_ids": { "type": "keyword" }, + "following_user_ids": { "type": "keyword" } + } + } + }`, + sql: ` + select + user_id, + json_build_object ( + 'follower_count', follower_count, + 'saved_track_ids', + ( + select + array_agg (save_item_id) + from + saves + where + save_type = 'track' + and is_delete = false + and user_id = users.user_id + ), + 'reposted_track_ids', + ( + select + array_agg (repost_item_id) + from + reposts + where + repost_type = 'track' + and is_delete = false + and user_id = users.user_id + ), + 'saved_playlist_ids', + ( + select + array_agg (save_item_id) + from + saves + where + save_type != 'track' + and is_delete = false + and user_id = users.user_id + ), + 'reposted_playlist_ids', + ( + select + array_agg (repost_item_id) + from + reposts + where + repost_type != 'track' + and is_delete = false + and user_id = users.user_id + ), + 'following_user_ids', + ( + select + array_agg (followee_user_id) + from + follows + where + is_delete = false + and follower_user_id = users.user_id + ) + ) as doc + from + aggregate_user users + where 1=1 + `, +} diff --git a/esindexer/tracks_index.go b/esindexer/tracks_index.go new file mode 100644 index 00000000..56872e63 --- /dev/null +++ b/esindexer/tracks_index.go @@ -0,0 +1,53 @@ +package esindexer + +var tracksConfig = collectionConfig{ + indexName: "tracks", + idColumn: "track_id", + mapping: ` + { + "mappings": { + "properties": { + "bpm": { "type": "float" } + } + } + }`, + sql: ` + SELECT + track_id, + json_build_object( + 'title', title, + 'genre', genre, + 'mood', mood, + 'duration', duration, + 'save_count', aggregate_track.save_count, + 'repost_count', aggregate_track.repost_count, + 'comment_count', aggregate_track.comment_count, + 'release_date', coalesce(release_date, tracks.created_at), + 'updated_at', tracks.updated_at, + 'blocknumber', tracks.blocknumber, + 'musical_key', musical_key, + 'bpm', bpm, + 'tags', string_to_array(tags, ','), + 'is_downloadable', is_downloadable, + 'has_stems', (select true from stems where parent_track_id = tracks.track_id limit 1), + 'download_conditions', download_conditions, + 'stream_conditions', stream_conditions, + 'user', json_build_object( + 'handle', users.handle, + 'name', users.name, + 'location', users.location, + 'follower_count', aggregate_user.follower_count, + 'is_verified', is_verified + ) + ) + FROM tracks + JOIN aggregate_track USING (track_id) + JOIN users ON owner_id = user_id + JOIN aggregate_user USING (user_id) + WHERE tracks.is_unlisted = false + AND tracks.is_delete = false + AND tracks.is_available = true + AND users.is_available = true + AND users.is_deactivated = false + `, +} diff --git a/esindexer/users_index.go b/esindexer/users_index.go new file mode 100644 index 00000000..f9f53857 --- /dev/null +++ b/esindexer/users_index.go @@ -0,0 +1,49 @@ +package esindexer + +var userConfig = collectionConfig{ + indexName: "users", + idColumn: "user_id", + sql: ` + SELECT + user_id, + json_build_object( + 'name', name, + 'handle', handle, + 'bio', bio, + 'location', location, + 'created_at', created_at, + 'updated_at', updated_at, + 'blocknumber', users.blocknumber, + 'is_verified', is_verified, + + 'track_count', track_count, + 'playlist_count', playlist_count, + 'follower_count', follower_count, + 'repost_count', repost_count, + 'track_save_count', track_save_count, + 'supporter_count', supporter_count, + 'supporting_count', supporting_count, + 'dominant_genre', dominant_genre, + 'dominant_genre_count', dominant_genre_count, + + 'tracks', ( + SELECT json_agg( + json_build_object( + 'title', title, + 'genre', genre, + 'mood', mood, + 'tags', string_to_array(tags, ',') + + -- todo: more track fields + ) + ) + FROM tracks + WHERE owner_id = users.user_id + ) + ) + FROM users + JOIN aggregate_user USING (user_id) + WHERE is_deactivated = false + AND is_available = true + `, +} diff --git a/go.mod b/go.mod index 5460b73c..5d6c0e2a 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,9 @@ toolchain go1.24.3 require ( github.com/AudiusProject/audiusd v0.0.0-20250604041839-b2c3c6c47a69 github.com/Doist/unfurlist v0.0.0-20250409100812-515f2735f8e5 + github.com/aquasecurity/esquery v0.2.0 github.com/axiomhq/axiom-go v0.23.0 + github.com/elastic/go-elasticsearch/v8 v8.18.0 github.com/ethereum/go-ethereum v1.15.8 github.com/gagliardetto/binary v0.8.0 github.com/gagliardetto/solana-go v1.12.1-0.20250314202648-ca3f5f643435 @@ -16,6 +18,7 @@ require ( github.com/gofiber/fiber/v2 v2.52.6 github.com/jackc/pgx-zap v0.0.0-20221202020421-94b1cb2f889f github.com/jackc/pgx/v5 v5.7.4 + github.com/jackc/pgxlisten v0.0.0-20241106001234-1d6f6656415c github.com/joho/godotenv v1.5.1 github.com/maypok86/otter v1.2.4 github.com/mcuadros/go-defaults v1.2.0 @@ -25,6 +28,8 @@ require ( github.com/stretchr/testify v1.10.0 github.com/test-go/testify v1.1.4 github.com/tidwall/gjson v1.18.0 + github.com/tidwall/pretty v1.2.1 + github.com/tidwall/sjson v1.2.5 github.com/valyala/fasthttp v1.59.0 go.uber.org/zap v1.27.0 golang.org/x/sync v0.13.0 @@ -68,9 +73,12 @@ require ( github.com/dolthub/maphash v0.1.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/dyatlov/go-opengraph v0.0.0-20210112100619-dae8665a5b09 // indirect + github.com/elastic/elastic-transport-go/v8 v8.7.0 // indirect + github.com/elastic/go-elasticsearch/v7 v7.6.0 // indirect github.com/ethereum/c-kzg-4844 v1.0.0 // indirect github.com/ethereum/go-verkle v0.2.2 // indirect github.com/fatih/color v1.18.0 // indirect + github.com/fatih/structs v1.1.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/gabriel-vasile/mimetype v1.4.9 // indirect github.com/gagliardetto/treeout v0.1.4 // indirect @@ -136,7 +144,6 @@ require ( github.com/supranational/blst v0.3.14 // indirect github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 // indirect github.com/tidwall/match v1.1.1 // indirect - github.com/tidwall/pretty v1.2.1 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasttemplate v1.2.2 // indirect go.etcd.io/bbolt v1.4.0-alpha.0.0.20240404170359-43604f3112c5 // indirect diff --git a/go.sum b/go.sum index 5597ce92..8d25dbea 100644 --- a/go.sum +++ b/go.sum @@ -20,6 +20,8 @@ github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129 h1:MzBOUgng9or github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129/go.mod h1:rFgpPQZYZ8vdbc+48xibu8ALc3yeyd64IhHS+PU6Yyg= github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA= github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA= +github.com/aquasecurity/esquery v0.2.0 h1:9WWXve95TE8hbm3736WB7nS6Owl8UGDeu+0jiyE9ttA= +github.com/aquasecurity/esquery v0.2.0/go.mod h1:VU+CIFR6C+H142HHZf9RUkp4Eedpo9UrEKeCQHWf9ao= github.com/artyom/autoflags v1.1.1 h1:8flRmpb7xpjLHFVcM+HN+cEEKLw+H5a2hABDbRvfG9A= github.com/artyom/autoflags v1.1.1/go.mod h1:Th9KgAVvFcYp7t8b//Pu21xHjExLpzr4SXCbwVbHL7Y= github.com/artyom/httpflags v1.2.0 h1:Eyx41cC1Z3dR/j68aHBEzpGT49cwzOOJix3hd/lk5ms= @@ -99,6 +101,12 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/dyatlov/go-opengraph v0.0.0-20210112100619-dae8665a5b09 h1:AQLr//nh20BzN3hIWj2+/Gt3FwSs8Nwo/nz4hMIcLPg= github.com/dyatlov/go-opengraph v0.0.0-20210112100619-dae8665a5b09/go.mod h1:nYia/MIs9OyvXXYboPmNOj0gVWo97Wx0sde+ZuKkoM4= +github.com/elastic/elastic-transport-go/v8 v8.7.0 h1:OgTneVuXP2uip4BA658Xi6Hfw+PeIOod2rY3GVMGoVE= +github.com/elastic/elastic-transport-go/v8 v8.7.0/go.mod h1:YLHer5cj0csTzNFXoNQ8qhtGY1GTvSqPnKWKaqQE3Hk= +github.com/elastic/go-elasticsearch/v7 v7.6.0 h1:sYpGLpEFHgLUKLsZUBfuaVI9QgHjS3JdH9fX4/z8QI8= +github.com/elastic/go-elasticsearch/v7 v7.6.0/go.mod h1:OJ4wdbtDNk5g503kvlHLyErCgQwwzmDtaFC4XyOxXA4= +github.com/elastic/go-elasticsearch/v8 v8.18.0 h1:ANNq1h7DEiPUaALb8+5w3baQzaS08WfHV0DNzp0VG4M= +github.com/elastic/go-elasticsearch/v8 v8.18.0/go.mod h1:WLqwXsJmQoYkoA9JBFeEwPkQhCfAZuUvfpdU/NvSSf0= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= @@ -111,6 +119,8 @@ github.com/ethereum/go-verkle v0.2.2 h1:I2W0WjnrFUIzzVPwm8ykY+7pL2d4VhlsePn4j7cn github.com/ethereum/go-verkle v0.2.2/go.mod h1:M3b90YRnzqKyyzBEWJGqj8Qff4IDeXnzFw0P9bFw3uk= github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= +github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo= +github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= @@ -225,8 +235,14 @@ github.com/jackc/pgx-zap v0.0.0-20221202020421-94b1cb2f889f h1:ahoGnXfh4wiCisojv github.com/jackc/pgx-zap v0.0.0-20221202020421-94b1cb2f889f/go.mod h1:m9tCxmy1PSUQa5o0aL4rQTowmJD1BK2Zc7dgnK/IrXc= github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg= github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= +github.com/jackc/pgxlisten v0.0.0-20241106001234-1d6f6656415c h1:bTgmg761ac9Ki27HoLx8IBvc+T+Qj6eptBpKahKIRT4= +github.com/jackc/pgxlisten v0.0.0-20241106001234-1d6f6656415c/go.mod h1:N4E1APLOYrbM11HH5kdqAjDa8RJWVwD3JqWpvH22h64= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/jgroeneveld/schema v1.0.0 h1:J0E10CrOkiSEsw6dfb1IfrDJD14pf6QLVJ3tRPl/syI= +github.com/jgroeneveld/schema v1.0.0/go.mod h1:M14lv7sNMtGvo3ops1MwslaSYgDYxrSmbzWIQ0Mr5rs= +github.com/jgroeneveld/trial v2.0.0+incompatible h1:d59ctdgor+VqdZCAiUfVN8K13s0ALDioG5DWwZNtRuQ= +github.com/jgroeneveld/trial v2.0.0+incompatible/go.mod h1:I6INLW96EN8WysNBXUFI3M4RIC8ePg9ntAc/Wy+U/+M= github.com/jmhodges/levigo v1.0.0 h1:q5EC36kV79HWeTBWsod3mG11EgStG3qArTKcvlksN1U= github.com/jmhodges/levigo v1.0.0/go.mod h1:Q6Qx+uH3RAqyK4rFQroq9RL7mdkABMcfhEI+nNuzMJQ= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= @@ -367,6 +383,7 @@ github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 h1:epCh84lMvA70 github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc= github.com/test-go/testify v1.1.4 h1:Tf9lntrKUMHiXQ07qBScBTSA0dhYQlu83hswqelv1iE= github.com/test-go/testify v1.1.4/go.mod h1:rH7cfJo/47vWGdi4GPj16x3/t1xGOj2YxzmNQzk2ghU= +github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= diff --git a/main.go b/main.go index eba2406e..46ade413 100644 --- a/main.go +++ b/main.go @@ -1,11 +1,27 @@ package main import ( + "fmt" + "os" + "slices" + "bridgerton.audius.co/api" "bridgerton.audius.co/config" + "bridgerton.audius.co/esindexer" ) func main() { + + if len(os.Args) > 1 && os.Args[1] == "reindex" { + collections := os.Args[2:] + drop := slices.Contains(collections, "drop") + fmt.Println("reindex", "drop", drop, "collections", collections) + + esindexer.ReindexLegacy(drop, collections...) + return + } + as := api.NewApiServer(config.Cfg) as.Serve() + } diff --git a/static/searchtest.html b/static/searchtest.html new file mode 100644 index 00000000..59aa1f56 --- /dev/null +++ b/static/searchtest.html @@ -0,0 +1,133 @@ + + +
+ +