mirror of
https://github.com/opencloud-eu/opencloud.git
synced 2026-12-05 05:43:36 -05:00
Merge pull request #4154 from opencloud-eu/fix/tags-listing-aggregation
fix(graph): list tags through a terms aggregation
This commit is contained in:
5 files changed
+64
-94
No files matched your search
@@ -1,68 +1,43 @@
|
||||
package svc
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
|
||||
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
|
||||
"github.com/go-chi/render"
|
||||
libregraph "github.com/opencloud-eu/libre-graph-api-go"
|
||||
"github.com/opencloud-eu/opencloud/pkg/conversions"
|
||||
searchmsg "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/search/v0"
|
||||
searchsvc "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0"
|
||||
"github.com/opencloud-eu/opencloud/services/graph/pkg/errorcode"
|
||||
revaCtx "github.com/opencloud-eu/reva/v3/pkg/ctx"
|
||||
"github.com/opencloud-eu/reva/v3/pkg/events"
|
||||
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
|
||||
"github.com/opencloud-eu/reva/v3/pkg/tags"
|
||||
libregraph "github.com/opencloud-eu/libre-graph-api-go"
|
||||
"go-micro.dev/v4/metadata"
|
||||
)
|
||||
|
||||
// maxListedTags is the maximum number of tags that GetTags returns. It keeps
|
||||
// the response small when many distinct tags are in use. Since the tags are
|
||||
// sorted before the list is cut, the same tags are always the ones returned.
|
||||
// the response small when many distinct tags are in use.
|
||||
const maxListedTags = 100
|
||||
|
||||
// listedTags returns the distinct tags of the given search matches, sorted in
|
||||
// byte order, and cut at maxListedTags.
|
||||
//
|
||||
// Byte order means that upper case comes before lower case ("Banana" before
|
||||
// "apple"). It is used on purpose instead of a case-insensitive order, which
|
||||
// would be nicer to read, because it is the order in which search engines sort
|
||||
// keyword values, e.g. an OpenSearch terms aggregation ordered by key. With the
|
||||
// same order here, the search can return just the first maxListedTags tags of
|
||||
// every space, and merging those lists still gives exactly the first
|
||||
// maxListedTags tags overall. With a case-insensitive order, that only works by
|
||||
// aggregating on a lowercased copy of the field, which needs a mapping change
|
||||
// and a reindex, and loses the original casing of the tags. Clients that want
|
||||
// another order for display can sort the list themselves.
|
||||
func listedTags(matches []*searchmsg.Match) []string {
|
||||
distinct := make(map[string]struct{})
|
||||
for _, match := range matches {
|
||||
for _, tag := range match.GetEntity().GetTags() {
|
||||
if tag != "" {
|
||||
distinct[tag] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// never nil: an empty list is rendered as "value": [], not left out
|
||||
list := slices.AppendSeq(make([]string, 0, len(distinct)), maps.Keys(distinct))
|
||||
slices.Sort(list)
|
||||
return list[:min(len(list), maxListedTags)]
|
||||
}
|
||||
|
||||
// GetTags returns the tags in use, see listedTags
|
||||
// GetTags returns the tags in use: the first maxListedTags in byte order,
|
||||
// upper case before lower case ("Banana" before "apple"). That is the order
|
||||
// of the keys of a terms aggregation, so the search can cut the list. Clients
|
||||
// that want another order for display can sort the list themselves.
|
||||
func (g Graph) GetTags(w http.ResponseWriter, r *http.Request) {
|
||||
th := r.Header.Get(revaCtx.TokenHeader)
|
||||
ctx := revaCtx.ContextSetToken(r.Context(), th)
|
||||
ctx = metadata.Set(ctx, revaCtx.TokenHeader, th)
|
||||
sr, err := g.searchService.Search(ctx, &searchsvc.SearchRequest{
|
||||
Query: "Tags:*",
|
||||
PageSize: conversions.ToPointer(int32(-1)),
|
||||
PageSize: conversions.ToPointer(int32(0)),
|
||||
Aggregations: []*searchsvc.AggregationOption{{
|
||||
Field: "Tags",
|
||||
Size: maxListedTags,
|
||||
BucketDefinition: &searchsvc.BucketDefinition{SortBy: searchsvc.BucketSortBy_BUCKET_SORT_BY_KEY_AS_STRING},
|
||||
}},
|
||||
})
|
||||
if err != nil {
|
||||
g.logger.Error().Err(err).Msg("Could not search for tags")
|
||||
@@ -70,8 +45,16 @@ func (g Graph) GetTags(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// never nil: an empty list is rendered as "value": [], not left out
|
||||
list := []string{}
|
||||
if aggs := sr.GetAggregations(); len(aggs) > 0 {
|
||||
for _, bucket := range aggs[0].GetBuckets() {
|
||||
list = append(list, bucket.GetKey())
|
||||
}
|
||||
}
|
||||
|
||||
tagCollection := libregraph.NewCollectionOfTags()
|
||||
tagCollection.Value = listedTags(sr.GetMatches())
|
||||
tagCollection.Value = list
|
||||
|
||||
render.Status(r, http.StatusOK)
|
||||
render.JSON(w, r, tagCollection)
|
||||
|
||||
@@ -3,7 +3,6 @@ package svc_test
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
|
||||
@@ -15,7 +14,6 @@ import (
|
||||
|
||||
"github.com/opencloud-eu/opencloud/pkg/log"
|
||||
"github.com/opencloud-eu/opencloud/pkg/shared"
|
||||
searchmsg "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/search/v0"
|
||||
searchsvc "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0"
|
||||
searchmocks "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0/mocks"
|
||||
"github.com/opencloud-eu/opencloud/services/graph/pkg/config/defaults"
|
||||
@@ -32,13 +30,13 @@ var _ = Describe("GetTags", func() {
|
||||
tape *httptest.ResponseRecorder
|
||||
)
|
||||
|
||||
// matchesWithTags returns one search match per argument, with the given tags
|
||||
matchesWithTags := func(tagsPerMatch ...[]string) []*searchmsg.Match {
|
||||
matches := make([]*searchmsg.Match, 0, len(tagsPerMatch))
|
||||
for _, tags := range tagsPerMatch {
|
||||
matches = append(matches, &searchmsg.Match{Entity: &searchmsg.Entity{Tags: tags}})
|
||||
// tagBuckets answers like the search does: one bucket per tag
|
||||
tagBuckets := func(tags ...string) *searchsvc.SearchResponse {
|
||||
buckets := make([]*searchsvc.Bucket, 0, len(tags))
|
||||
for _, tag := range tags {
|
||||
buckets = append(buckets, &searchsvc.Bucket{Key: tag, Count: 1})
|
||||
}
|
||||
return matches
|
||||
return &searchsvc.SearchResponse{Aggregations: []*searchsvc.AggregationResult{{Field: "Tags", Buckets: buckets}}}
|
||||
}
|
||||
|
||||
getTags := func() []string {
|
||||
@@ -72,68 +70,33 @@ var _ = Describe("GetTags", func() {
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
|
||||
It("asks the search for all tagged resources", func() {
|
||||
It("asks the search for the first tags in byte order, without matches", func() {
|
||||
searchService.EXPECT().Search(mock.Anything, mock.MatchedBy(func(req *searchsvc.SearchRequest) bool {
|
||||
return req.GetQuery() == "Tags:*" && req.GetPageSize() == -1
|
||||
aggs := req.GetAggregations()
|
||||
return req.GetQuery() == "Tags:*" && req.PageSize != nil && req.GetPageSize() == 0 &&
|
||||
len(aggs) == 1 && aggs[0].GetField() == "Tags" &&
|
||||
aggs[0].GetSize() == int32(service.MaxListedTagsForTest) &&
|
||||
aggs[0].GetBucketDefinition().GetSortBy() == searchsvc.BucketSortBy_BUCKET_SORT_BY_KEY_AS_STRING &&
|
||||
!aggs[0].GetBucketDefinition().GetIsDescending()
|
||||
})).Return(&searchsvc.SearchResponse{}, nil)
|
||||
|
||||
Expect(getTags()).To(BeEmpty())
|
||||
})
|
||||
|
||||
It("renders an empty list when no tags are in use", func() {
|
||||
searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(&searchsvc.SearchResponse{}, nil)
|
||||
searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(tagBuckets(), nil)
|
||||
|
||||
svc.GetTags(tape, httptest.NewRequest(http.MethodGet, "/graph/v1.0/extensions/org.libregraph/tags", nil))
|
||||
Expect(tape.Code).To(Equal(http.StatusOK))
|
||||
Expect(tape.Body.String()).To(MatchJSON(`{"value": []}`))
|
||||
})
|
||||
|
||||
It("lists every tag once", func() {
|
||||
searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(&searchsvc.SearchResponse{
|
||||
Matches: matchesWithTags([]string{"work", "draft"}, []string{"draft", ""}, nil, []string{"work"}),
|
||||
}, nil)
|
||||
|
||||
Expect(getTags()).To(Equal([]string{"draft", "work"}))
|
||||
})
|
||||
|
||||
It("sorts the tags in byte order, upper case before lower case", func() {
|
||||
searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(&searchsvc.SearchResponse{
|
||||
Matches: matchesWithTags([]string{"apple", "cherry"}, []string{"Apple", "Banana"}),
|
||||
}, nil)
|
||||
It("lists the tags as the search orders them", func() {
|
||||
searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(tagBuckets("Apple", "Banana", "apple", "cherry"), nil)
|
||||
|
||||
Expect(getTags()).To(Equal([]string{"Apple", "Banana", "apple", "cherry"}))
|
||||
})
|
||||
|
||||
It("returns the same list for the same tags, whatever the order of the search results", func() {
|
||||
first := matchesWithTags([]string{"c", "a"}, []string{"b"})
|
||||
reversed := matchesWithTags([]string{"b"}, []string{"a", "c"})
|
||||
|
||||
searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(&searchsvc.SearchResponse{Matches: first}, nil).Once()
|
||||
firstResult := getTags()
|
||||
|
||||
tape = httptest.NewRecorder()
|
||||
searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(&searchsvc.SearchResponse{Matches: reversed}, nil).Once()
|
||||
Expect(getTags()).To(Equal(firstResult))
|
||||
})
|
||||
|
||||
It("returns only the first tags in sort order when more tags are in use than it lists", func() {
|
||||
limit := service.MaxListedTagsForTest
|
||||
// one more tag than listed, spread over several matches, in descending order
|
||||
all := make([]string, 0, limit+1)
|
||||
for i := limit; i >= 0; i-- {
|
||||
all = append(all, fmt.Sprintf("tag%03d", i))
|
||||
}
|
||||
searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(&searchsvc.SearchResponse{
|
||||
Matches: matchesWithTags(all[:limit/2], all[limit/2:]),
|
||||
}, nil)
|
||||
|
||||
listed := getTags()
|
||||
Expect(listed).To(HaveLen(limit))
|
||||
Expect(listed[0]).To(Equal("tag000"))
|
||||
Expect(listed[limit-1]).To(Equal(fmt.Sprintf("tag%03d", limit-1)))
|
||||
Expect(listed).ToNot(ContainElement(fmt.Sprintf("tag%03d", limit)))
|
||||
})
|
||||
|
||||
It("fails when the search fails", func() {
|
||||
searchService.EXPECT().Search(mock.Anything, mock.Anything).Return(nil, errors.New("search is down"))
|
||||
|
||||
|
||||
@@ -284,6 +284,16 @@ var _ = Describe("Merge and Finalize", func() {
|
||||
Expect(render(got)).To(Equal([]string{"audio.artist Saxon=2"}))
|
||||
})
|
||||
|
||||
It("cuts to the first keys in byte order across spaces, upper case before lower case", func() {
|
||||
opts := []*searchsvc.AggregationOption{{
|
||||
Field: "Tags", Size: 3,
|
||||
BucketDefinition: &searchsvc.BucketDefinition{SortBy: searchsvc.BucketSortBy_BUCKET_SORT_BY_KEY_AS_STRING},
|
||||
}}
|
||||
a := []*searchsvc.AggregationResult{buckets("Tags", bucket("cherry", 1), bucket("apple", 1), bucket("Banana", 1))}
|
||||
b := []*searchsvc.AggregationResult{buckets("Tags", bucket("apple", 1), bucket("Apple", 1))}
|
||||
Expect(render(merged(opts, a, b))).To(Equal([]string{"Tags Apple=1", "Tags Banana=1", "Tags apple=2"}))
|
||||
})
|
||||
|
||||
It("shapes the buckets of a sub-aggregation by its own definition", func() {
|
||||
opts := []*searchsvc.AggregationOption{{Field: "audio.artist", SubAggregations: []*searchsvc.AggregationOption{{
|
||||
Field: "audio.album", Size: 2,
|
||||
|
||||
@@ -856,7 +856,7 @@ Fixtures:
|
||||
- `b.jpg`, MimeType = image/jpeg
|
||||
- `c.jpg`, MimeType = image/jpeg
|
||||
- `d.jpg`, MimeType = image/jpeg
|
||||
- `live.txt`
|
||||
- `live.txt`, Tags = Apple, apple, Banana
|
||||
|
||||
| Case | Query | expected | bleve | OpenSearch | same? |
|
||||
|---|---|---|---|---|---|
|
||||
@@ -879,6 +879,7 @@ Fixtures:
|
||||
| AGG-20 | `mediatype:audio` reads `album buckets in audio.year ranges in artist buckets` | audio.arti... Steel=2, audio.arti.....1980=0, audio.arti.....1980=2, audio.arti...1980..=0, audio.arti...1980..=3, audio.arti...Bomber=2, audio.arti...Spades=1, audio.artist Motörhead=3, … +1 more | audio.arti... Steel=2, audio.arti.....1980=0, audio.arti.....1980=2, audio.arti...1980..=0, audio.arti...1980..=3, audio.arti...Bomber=2, audio.arti...Spades=1, audio.artist Motörhead=3, … +1 more | audio.arti... Steel=2, audio.arti.....1980=0, audio.arti.....1980=2, audio.arti...1980..=0, audio.arti...1980..=3, audio.arti...Bomber=2, audio.arti...Spades=1, audio.artist Motörhead=3, … +1 more | ✅ |
|
||||
| AGG-21 | `mediatype:image` reads `a metric without a single value has none` | audio.year avg none, audio.year min none, audio.year sum none | audio.year avg none, audio.year min none, audio.year sum none | audio.year avg none, audio.year min none, audio.year sum none | ✅ |
|
||||
| AGG-22 | `mediatype:audio` reads `filtered to the Saxon bucket, as many matches as the bucket counted` | a.mp3, audio.artist Saxon=2, b.mp3 | a.mp3, audio.artist Saxon=2, b.mp3 | a.mp3, audio.artist Saxon=2, b.mp3 | ✅ |
|
||||
| AGG-49 | `name:live.txt` reads `tags keep their case, Apple and apple are two buckets` | Tags Apple=1, Tags Banana=1, Tags apple=1 | Tags Apple=1, Tags Banana=1, Tags apple=1 | Tags Apple=1, Tags Banana=1, Tags apple=1 | ✅ |
|
||||
| AGG-23 | `mediatype:audio` reads `filtered to saxon, a bucket key matches case-sensitively` | no match | no match | no match | ✅ |
|
||||
| AGG-46 | `mediatype:audio` reads `filtered to a fractional key on a whole-number field, no match and no error` | no match | no match | no match | ✅ |
|
||||
| AGG-24 | `mediatype:audio` reads `filtered to the Saxon or the Motörhead bucket` | a.mp3, b.mp3, c.mp3, d.mp3, e.mp3 | a.mp3, b.mp3, c.mp3, d.mp3, e.mp3 | a.mp3, b.mp3, c.mp3, d.mp3, e.mp3 | ✅ |
|
||||
@@ -919,6 +920,7 @@ Fixtures:
|
||||
|
||||
| Case | Query | expected | bleve | OpenSearch | same? |
|
||||
|---|---|---|---|---|---|
|
||||
| AGG-47 | `Tags:*` reads `one bucket per tag, whichever match carries it` | 150 items | Tags tag-000=53, Tags tag-001=53, Tags tag-002=53, Tags tag-003=53, Tags tag-004=53, Tags tag-005=53, Tags tag-006=53, Tags tag-007=53, … +142 more | Tags tag-000=53, Tags tag-001=53, Tags tag-002=53, Tags tag-003=53, Tags tag-004=53, Tags tag-005=53, Tags tag-006=53, Tags tag-007=53, … +142 more | ✅ |
|
||||
| AGG-17 | `mediatype:audio` reads `one bucket per artist, cardinality above the page size` | 10050 items | audio.arti...-00000=1, audio.arti...-00001=1, audio.arti...-00002=1, audio.arti...-00003=1, audio.arti...-00004=1, audio.arti...-00005=1, audio.arti...-00006=1, audio.arti...-00007=1, … +10042 more | audio.arti...-00000=1, audio.arti...-00001=1, audio.arti...-00002=1, audio.arti...-00003=1, audio.arti...-00004=1, audio.arti...-00005=1, audio.arti...-00006=1, audio.arti...-00007=1, … +10042 more | ✅ |
|
||||
| AGG-42 | `mediatype:audio` reads `the total counts every match` | 1 of 10050 matches | 1 of 10050 matches | 1 of 10050 matches | ✅ |
|
||||
| AGG-43 | `mediatype:audio` reads `a page reaching beyond the first 10000 matches` | 10001 of 10050 matches | 10001 of 10050 matches | bad request | ❌ known |
|
||||
|
||||
@@ -95,7 +95,7 @@ func aggregationFixtures() []search.Resource {
|
||||
photo("c.jpg", "2018-09-01T12:00:00Z"),
|
||||
photo("d.jpg", "2021-08-11T08:00:00Z"),
|
||||
// no audio mime type: stays out of the mediatype:audio cases
|
||||
fixtureDoc("live.txt", withAudio(&libregraph.Audio{Artist: libregraph.PtrString(`Wh*t? "Live"`)})),
|
||||
fixtureDoc("live.txt", withAudio(&libregraph.Audio{Artist: libregraph.PtrString(`Wh*t? "Live"`)}), withTags("Apple", "apple", "Banana")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -271,6 +271,9 @@ func aggregationCases() []aggCase {
|
||||
filters: []*searchService.AggregationFilter{terms("audio.artist", "Saxon")},
|
||||
aggs: []*searchService.AggregationOption{{Field: "audio.artist"}},
|
||||
want: []string{"a.mp3", "b.mp3", "audio.artist Saxon=2"}},
|
||||
{id: 49, query: "name:live.txt", reads: "tags keep their case, Apple and apple are two buckets",
|
||||
aggs: []*searchService.AggregationOption{{Field: "Tags"}},
|
||||
want: []string{"Tags Apple=1", "Tags Banana=1", "Tags apple=1"}},
|
||||
{id: 23, query: "mediatype:audio", reads: "filtered to saxon, a bucket key matches case-sensitively",
|
||||
filters: []*searchService.AggregationFilter{terms("audio.artist", "saxon")}},
|
||||
{id: 46, query: "mediatype:audio", reads: "filtered to a fractional key on a whole-number field, no match and no error",
|
||||
@@ -390,7 +393,12 @@ func renderAggregation(prefix string, a *searchService.AggregationResult) []stri
|
||||
func cardinalityFixtures() []search.Resource {
|
||||
docs := make([]search.Resource, 0, 10050)
|
||||
for i := 0; i < 10050; i++ {
|
||||
docs = append(docs, song(fmt.Sprintf("card-%05d.mp3", i), fmt.Sprintf("artist-%05d", i), "Singles", int32(1950+i%50)))
|
||||
// tags only beyond the first 1000 songs, the page OpenSearch returns for "all matches"
|
||||
var tagged []fixtureOption
|
||||
if i >= 2000 {
|
||||
tagged = append(tagged, withTags(fmt.Sprintf("tag-%03d", i%150)))
|
||||
}
|
||||
docs = append(docs, song(fmt.Sprintf("card-%05d.mp3", i), fmt.Sprintf("artist-%05d", i), "Singles", int32(1950+i%50), tagged...))
|
||||
}
|
||||
return docs
|
||||
}
|
||||
@@ -406,7 +414,11 @@ func nested(fields ...string) *searchService.AggregationOption {
|
||||
|
||||
func cardinalityCases() []aggCase {
|
||||
count := 10050
|
||||
tags := 150
|
||||
return []aggCase{
|
||||
{id: 47, query: "Tags:*", reads: "one bucket per tag, whichever match carries it",
|
||||
aggs: []*searchService.AggregationOption{{Field: "Tags"}},
|
||||
wantCount: &tags},
|
||||
{id: 17, query: "mediatype:audio", reads: "one bucket per artist, cardinality above the page size",
|
||||
aggs: []*searchService.AggregationOption{{Field: "audio.artist"}},
|
||||
wantCount: &count},
|
||||
|
||||
Reference in new issue
Block a user