Merge pull request #3835 from opencloud-eu/refactor/search-engine-ast

refactor(search): hand the engines the parsed query
This commit is contained in:
Dominik Schmidt authored and GitHub committed 2026-12-01 14:48:06 +01:00
commit 492412ca56
24 files changed
+712 -331

No files matched your search

+8 -13
View File
@@ -17,7 +17,6 @@ import (
"github.com/opencloud-eu/reva/v3/pkg/utils"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/opencloud-eu/opencloud/pkg/kql"
"github.com/opencloud-eu/opencloud/pkg/log"
"github.com/opencloud-eu/opencloud/services/search/pkg/aggregation"
"github.com/opencloud-eu/opencloud/services/search/pkg/mapping"
@@ -26,6 +25,7 @@ import (
searchMessage "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/search/v0"
searchService "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0"
searchQuery "github.com/opencloud-eu/opencloud/services/search/pkg/query"
bleveQuery "github.com/opencloud-eu/opencloud/services/search/pkg/query/bleve"
)
const defaultBatchSize = 50
@@ -33,17 +33,15 @@ const defaultBatchSize = 50
var _ search.Engine = (*Backend)(nil) // ensure Backend implements Engine
type Backend struct {
index *serialIndex
queryCreator searchQuery.Creator[query.Query]
log log.Logger
optimizeMu sync.Mutex
index *serialIndex
log log.Logger
optimizeMu sync.Mutex
}
func NewBackend(index bleve.Index, queryCreator searchQuery.Creator[query.Query], log log.Logger) *Backend {
func NewBackend(index bleve.Index, log log.Logger) *Backend {
return &Backend{
index: &serialIndex{bleveIndex: index},
queryCreator: queryCreator,
log: log,
index: &serialIndex{bleveIndex: index},
log: log,
}
}
@@ -68,11 +66,8 @@ func (i *serialIndex) Batch(b *bleve.Batch) error {
// Search executes a search request operation within the index.
func (b *Backend) Search(ctx context.Context, sir *search.IndexQuery) (*search.IndexResult, error) {
createdQuery, err := b.queryCreator.Create(sir.Query)
createdQuery, err := bleveQuery.Compiler{}.Compile(searchQuery.Normalize(sir.Query, searchQuery.ResolveField))
if err != nil {
if kql.IsValidationError(err) {
return nil, errtypes.BadRequest(err.Error())
}
return nil, err
}
+32 -4
View File
@@ -10,10 +10,11 @@ import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/opencloud-eu/opencloud/pkg/kql"
"github.com/opencloud-eu/opencloud/pkg/log"
"github.com/opencloud-eu/opencloud/services/search/pkg/bleve"
"github.com/opencloud-eu/opencloud/services/search/pkg/config/defaults"
"github.com/opencloud-eu/opencloud/services/search/pkg/content"
bleveQuery "github.com/opencloud-eu/opencloud/services/search/pkg/query/bleve"
"github.com/opencloud-eu/opencloud/services/search/pkg/search"
)
@@ -34,7 +35,7 @@ var _ = Describe("Bleve", func() {
idx, err = bleveSearch.NewMemOnly(mapping)
Expect(err).ToNot(HaveOccurred())
eng = bleve.NewBackend(idx, bleveQuery.DefaultCreator, log.Logger{})
eng = bleve.NewBackend(idx, log.Logger{})
Expect(err).ToNot(HaveOccurred())
rootResource = search.Resource{
@@ -64,6 +65,31 @@ var _ = Describe("Bleve", func() {
})
Describe("Search", func() {
It("applies the default query template", func() {
keep := func(id, path, name string) search.Resource {
return search.Resource{ID: id, RootID: rootResource.ID, Path: path, Document: content.Document{Name: name, Tags: []string{"keep"}}}
}
for _, r := range []search.Resource{
keep(rootResource.ID, ".", "root"),
keep("1$2!5", "./.space/readme.md", "readme.md"),
keep("1$2!6", "./child.pdf", "child.pdf"),
} {
Expect(eng.Upsert(r.ID, r)).To(Succeed())
}
template, err := search.ParseQueryTemplate(defaults.DefaultConfig().QueryTemplate)
Expect(err).ToNot(HaveOccurred())
query, err := search.ParseQuery(`tag:keep`)
Expect(err).ToNot(HaveOccurred())
space := &sprovider.StorageSpace{SpaceType: "personal", Root: &sprovider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "2"}}
res, err := eng.Search(context.Background(), &search.IndexQuery{Query: template.Expand(query, space)})
Expect(err).ToNot(HaveOccurred())
Expect(res.Matches).To(HaveLen(1))
Expect(res.Matches[0].Entity.Name).To(Equal("child.pdf"))
})
})
Describe("PurgeSpace", func() {
It("takes every record of that space out of the index", func() {
otherSpace := search.Resource{
@@ -140,7 +166,9 @@ var _ = Describe("Bleve", func() {
Describe("Update", func() {
tagHits := func(tag string) []string {
res, err := eng.Search(context.Background(), &search.IndexQuery{Query: `tag:("` + tag + `")`})
query, err := kql.Builder{}.Build(`tag:("` + tag + `")`)
Expect(err).ToNot(HaveOccurred())
res, err := eng.Search(context.Background(), &search.IndexQuery{Query: query})
Expect(err).ToNot(HaveOccurred())
var ids []string
for _, match := range res.Matches {
@@ -189,7 +217,7 @@ var _ = Describe("Bleve", func() {
Describe("New", func() {
It("returns a new index instance", func() {
b := bleve.NewBackend(idx, bleveQuery.DefaultCreator, log.Logger{})
b := bleve.NewBackend(idx, log.Logger{})
Expect(b).ToNot(BeNil())
})
})
+1 -2
View File
@@ -17,7 +17,6 @@ import (
"github.com/opencloud-eu/opencloud/pkg/log"
"github.com/opencloud-eu/opencloud/services/search/pkg/bleve"
"github.com/opencloud-eu/opencloud/services/search/pkg/content"
bleveQuery "github.com/opencloud-eu/opencloud/services/search/pkg/query/bleve"
"github.com/opencloud-eu/opencloud/services/search/pkg/search"
)
@@ -126,7 +125,7 @@ var _ = Describe("Batch", func() {
Describe("Push", func() {
It("runs one batch at a time when several are pushed together", func() {
probe := &batchProbe{bleveIndex: idx}
eng := bleve.NewBackend(probe, bleveQuery.DefaultCreator, log.NopLogger())
eng := bleve.NewBackend(probe, log.NopLogger())
var wg sync.WaitGroup
for i := range 4 {
+2 -3
View File
@@ -12,7 +12,6 @@ import (
"github.com/opencloud-eu/opencloud/pkg/log"
"github.com/opencloud-eu/opencloud/services/search/pkg/bleve"
"github.com/opencloud-eu/opencloud/services/search/pkg/content"
bleveQuery "github.com/opencloud-eu/opencloud/services/search/pkg/query/bleve"
"github.com/opencloud-eu/opencloud/services/search/pkg/search"
)
@@ -34,7 +33,7 @@ var _ = Describe("Optimize", func() {
idx, _, err := bleve.NewIndex(GinkgoT().TempDir(), log.NopLogger())
Expect(err).ToNot(HaveOccurred())
DeferCleanup(idx.Close)
return bleve.NewBackend(idx, bleveQuery.DefaultCreator, log.NopLogger()), idx
return bleve.NewBackend(idx, log.NopLogger()), idx
}
It("merges the segments of the index into one and keeps the documents", func() {
@@ -79,7 +78,7 @@ var _ = Describe("Optimize", func() {
Expect(err).ToNot(HaveOccurred())
DeferCleanup(idx.Close)
eng := bleve.NewBackend(idx, bleveQuery.DefaultCreator, log.NopLogger())
eng := bleve.NewBackend(idx, log.NopLogger())
Expect(eng.Optimize(context.Background())).To(MatchError(search.ErrOptimizeUnsupported))
})
})
+5 -3
View File
@@ -20,7 +20,6 @@ import (
"github.com/opencloud-eu/opencloud/services/search/pkg/content"
"github.com/opencloud-eu/opencloud/services/search/pkg/metrics"
"github.com/opencloud-eu/opencloud/services/search/pkg/opensearch"
bleveQuery "github.com/opencloud-eu/opencloud/services/search/pkg/query/bleve"
"github.com/opencloud-eu/opencloud/services/search/pkg/search"
"github.com/opencloud-eu/opencloud/services/search/pkg/server/debug"
"github.com/opencloud-eu/opencloud/services/search/pkg/server/grpc"
@@ -80,7 +79,7 @@ func Server(cfg *config.Config) *cobra.Command {
}
}()
eng = bleve.NewBackend(idx, bleveQuery.DefaultCreator, logger)
eng = bleve.NewBackend(idx, logger)
case "open-search":
client, err := opensearch.NewClient(cfg.Engine.OpenSearch.Client)
if err != nil {
@@ -122,7 +121,10 @@ func Server(cfg *config.Config) *cobra.Command {
return fmt.Errorf("unknown search extractor: %s", cfg.Extractor.Type)
}
ss := search.NewService(selector, eng, extractor, mtrcs, logger, cfg)
ss, err := search.NewService(selector, eng, extractor, mtrcs, logger, cfg)
if err != nil {
return err
}
// The KV bucket is used to remember spaces that were skipped during
// (re)indexing because they were disabled. It is shared between the gRPC
@@ -2,17 +2,11 @@ package parser
import (
"errors"
"fmt"
"strings"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
occfg "github.com/opencloud-eu/opencloud/pkg/config"
"github.com/opencloud-eu/opencloud/pkg/kql"
"github.com/opencloud-eu/opencloud/pkg/shared"
"github.com/opencloud-eu/opencloud/services/search/pkg/config"
"github.com/opencloud-eu/opencloud/services/search/pkg/config/defaults"
"github.com/opencloud-eu/opencloud/services/search/pkg/search"
"github.com/opencloud-eu/opencloud/pkg/config/envdecode"
)
@@ -55,31 +49,5 @@ func Validate(cfg *config.Config) error {
return shared.MissingServiceAccountSecret(cfg.Service.Name)
}
return validateQueryTemplate(cfg.QueryTemplate)
}
func validateQueryTemplate(template string) error {
if template == "" {
return nil
}
if strings.Count(template, config.QueryPlaceholder) != 1 {
return errors.New("search query template: must contain " + config.QueryPlaceholder + " exactly once")
}
wrapped := "(" + config.QueryPlaceholder + ")"
if !strings.Contains(template, wrapped) {
return errors.New("search query template: " + config.QueryPlaceholder + " must be wrapped as " + wrapped)
}
expanded := search.ExpandQueryTemplate(template, "a", &provider.StorageSpace{})
if strings.Contains(expanded, "{{") || strings.Contains(expanded, "}}") {
return errors.New("search query template: unknown placeholder")
}
if _, err := (kql.Builder{}).Build(expanded); err != nil {
return fmt.Errorf("search query template: %w", err)
}
return nil
}
@@ -1,27 +0,0 @@
package parser
import "testing"
func TestValidateQueryTemplate(t *testing.T) {
for template, valid := range map[string]bool{
"": true,
`({{.QUERY}})`: true,
`({{.QUERY}}) AND (NOT path:"./.space" AND NOT id:{{.SPACE_ROOT_PERSONAL}})`: true,
`({{.QUERY}}) OR mediatype:document`: true,
`({{.QUERY}}) AND NOT name:"a(b"`: true,
`{{.QUERY}}`: false,
`{{.QUERY}} AND NOT mediatype:folder`: false,
`({{.QUERY}}) OR ({{.QUERY}})`: false,
`({{.QUERY}}) AND {{.QUERY}}`: false,
`NOT mediatype:folder`: false,
`({{.QUERY}}) AND NOT id:{{.SPACE_ROOT_GRANT}}`: false,
`({{.QUERY}}) AND NOT id:{{.SPACE_ROOT_PERSONAL}`: false,
`(({{.QUERY}})`: false,
`({{.QUERY}}) AND AND`: false,
`({{.QUERY}}) AND`: false,
} {
if err := validateQueryTemplate(template); (err == nil) != valid {
t.Errorf("validateQueryTemplate(%q) = %v, want valid %v", template, err, valid)
}
}
}
+1 -5
View File
@@ -20,7 +20,6 @@ import (
"github.com/opencloud-eu/reva/v3/pkg/utils"
"github.com/opencloud-eu/opencloud/pkg/conversions"
"github.com/opencloud-eu/opencloud/pkg/kql"
"github.com/opencloud-eu/opencloud/pkg/log"
searchMessage "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/search/v0"
"github.com/opencloud-eu/opencloud/services/search/pkg/aggregation"
@@ -86,10 +85,7 @@ func NewBackend(ctx context.Context, name string, client *opensearchgoAPI.Client
func (b *Backend) Search(ctx context.Context, sir *search.IndexQuery) (*search.IndexResult, error) {
boolQuery, err := convert.KQLToOpenSearchBoolQuery(sir.Query)
switch {
case kql.IsValidationError(err):
return nil, errtypes.BadRequest(err.Error())
case err != nil:
if err != nil {
return nil, fmt.Errorf("failed to convert KQL query to OpenSearch bool query: %w", err)
}
+57 -3
View File
@@ -8,6 +8,7 @@ import (
"time"
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
sprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
opensearchgo "github.com/opensearch-project/opensearch-go/v4"
@@ -15,8 +16,11 @@ import (
revactx "github.com/opencloud-eu/reva/v3/pkg/ctx"
"github.com/opencloud-eu/opencloud/pkg/kql"
"github.com/opencloud-eu/opencloud/pkg/log"
"github.com/opencloud-eu/opencloud/services/search/internal/opensearchtest"
"github.com/opencloud-eu/opencloud/services/search/pkg/config/defaults"
"github.com/opencloud-eu/opencloud/services/search/pkg/content"
"github.com/opencloud-eu/opencloud/services/search/pkg/opensearch"
"github.com/opencloud-eu/opencloud/services/search/pkg/search"
)
@@ -48,6 +52,50 @@ var _ = Describe("Backend", func() {
})
})
Describe("Search", func() {
const indexName = "opencloud-test-engine-search"
var (
tc *opensearchtest.TestClient
backend *opensearch.Backend
)
BeforeEach(func() {
physical := opensearch.VersionedIndexName(indexName)
tc = opensearchtest.NewDefaultTestClient(GinkgoTB(), defaultConfig.Engine.OpenSearch.Client)
tc.Require.IndicesReset([]string{physical})
deleteIndexOnCleanup(tc, physical)
var err error
backend, err = opensearch.NewBackend(context.Background(), indexName, tc.Client(), log.NopLogger())
Expect(err).ToNot(HaveOccurred())
})
It("applies the default query template", func() {
keep := func(id, path, name string) search.Resource {
return search.Resource{ID: id, RootID: "1$2!2", Path: path, Document: content.Document{Name: name, Tags: []string{"keep"}}}
}
for _, r := range []search.Resource{
keep("1$2!2", ".", "root"),
keep("1$2!5", "./.space/readme.md", "readme.md"),
keep("1$2!6", "./child.pdf", "child.pdf"),
} {
Expect(backend.Upsert(r.ID, r)).To(Succeed())
}
template, err := search.ParseQueryTemplate(defaults.DefaultConfig().QueryTemplate)
Expect(err).ToNot(HaveOccurred())
query, err := search.ParseQuery(`tag:keep`)
Expect(err).ToNot(HaveOccurred())
space := &sprovider.StorageSpace{SpaceType: "personal", Root: &sprovider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "2"}}
res, err := backend.Search(context.Background(), &search.IndexQuery{Query: template.Expand(query, space)})
Expect(err).ToNot(HaveOccurred())
Expect(res.Matches).To(HaveLen(1))
Expect(res.Matches[0].Entity.Name).To(Equal("child.pdf"))
})
})
Describe("Upsert", func() {
const indexName = "opencloud-test-engine-upsert"
@@ -151,7 +199,9 @@ var _ = Describe("Backend", func() {
})
tagHits := func(tag string) int {
res, err := backend.Search(context.Background(), &search.IndexQuery{Query: `tag:("` + tag + `")`})
query, err := kql.Builder{}.Build(`tag:("` + tag + `")`)
Expect(err).ToNot(HaveOccurred())
res, err := backend.Search(context.Background(), &search.IndexQuery{Query: query})
Expect(err).ToNot(HaveOccurred())
return len(res.Matches)
}
@@ -215,9 +265,13 @@ var _ = Describe("Backend", func() {
Expect(err).ToNot(HaveOccurred())
ctx := revactx.ContextSetUser(context.Background(), &userv1beta1.User{Id: &userv1beta1.UserId{OpaqueId: "einstein"}})
_, err = backend.Search(ctx, &search.IndexQuery{Query: "name:a"})
query, err := kql.Builder{}.Build("name:a")
Expect(err).ToNot(HaveOccurred())
_, err = backend.Search(context.Background(), &search.IndexQuery{Query: "name:a"})
_, err = backend.Search(ctx, &search.IndexQuery{Query: query})
Expect(err).ToNot(HaveOccurred())
query, err = kql.Builder{}.Build("name:a")
Expect(err).ToNot(HaveOccurred())
_, err = backend.Search(context.Background(), &search.IndexQuery{Query: query})
Expect(err).ToNot(HaveOccurred())
Expect(searches.preferences).To(Equal([]string{"user-einstein", ""}))
@@ -3,7 +3,7 @@ package convert
import (
"fmt"
"github.com/opencloud-eu/opencloud/pkg/kql"
"github.com/opencloud-eu/opencloud/pkg/ast"
"github.com/opencloud-eu/opencloud/services/search/pkg/opensearch/internal/osu"
"github.com/opencloud-eu/opencloud/services/search/pkg/query"
)
@@ -12,12 +12,7 @@ var (
ErrUnsupportedNodeType = fmt.Errorf("unsupported node type")
)
func KQLToOpenSearchBoolQuery(kqlQuery string) (*osu.BoolQuery, error) {
kqlAst, err := kql.Builder{}.Build(kqlQuery)
if err != nil {
return nil, err
}
func KQLToOpenSearchBoolQuery(kqlAst *ast.Ast) (*osu.BoolQuery, error) {
// shared lowering: field resolution, media-type expansion, value lowercasing.
kqlAst = query.Normalize(kqlAst, query.ResolveField)
@@ -11,7 +11,6 @@ import (
libregraph "github.com/opencloud-eu/libre-graph-api-go"
"github.com/opencloud-eu/reva/v3/pkg/errtypes"
"github.com/opencloud-eu/opencloud/pkg/conversions"
searchService "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0"
"github.com/opencloud-eu/opencloud/services/search/pkg/aggregation"
"github.com/opencloud-eu/opencloud/services/search/pkg/search"
@@ -451,14 +450,10 @@ var _ = Describe("Aggregations", func() {
Skip(e.unavailable)
}
request := &search.IndexQuery{
Query: c.query,
Aggregations: c.aggs,
AggregationFilters: c.filters,
}
if c.pageSize != 0 {
request.PageSize = conversions.ToPointer(c.pageSize)
}
request, err := query(c.query, nil, c.pageSize)
Expect(err).NotTo(HaveOccurred(), "the query of an aggregation case has to parse")
request.Aggregations = c.aggs
request.AggregationFilters = c.filters
resp, err := e.backend.Search(context.Background(), request)
answer := renderAggregations(resp, err)
if err == nil && (len(c.filters) > 0 || c.listMatches) {
+31 -6
View File
@@ -13,12 +13,12 @@ import (
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
opensearchgoAPI "github.com/opensearch-project/opensearch-go/v4/opensearchapi"
"github.com/opencloud-eu/opencloud/pkg/conversions"
"github.com/opencloud-eu/opencloud/pkg/log"
searchMessage "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/search/v0"
"github.com/opencloud-eu/opencloud/services/search/internal/opensearchtest"
bleveEngine "github.com/opencloud-eu/opencloud/services/search/pkg/bleve"
"github.com/opencloud-eu/opencloud/services/search/pkg/opensearch"
bleveQuery "github.com/opencloud-eu/opencloud/services/search/pkg/query/bleve"
"github.com/opencloud-eu/opencloud/services/search/pkg/search"
)
@@ -81,7 +81,7 @@ func newBleve(fixtures []search.Resource) testEngine {
Expect(err).NotTo(HaveOccurred(), "failed to create the bleve index")
DeferCleanup(func() { _ = idx.Close() })
backend := bleveEngine.NewBackend(idx, bleveQuery.DefaultCreator, log.Logger{})
backend := bleveEngine.NewBackend(idx, log.Logger{})
load(backend, fixtures)
return testEngine{name: "bleve", backend: backend, settle: func() {}}
@@ -167,10 +167,35 @@ func resourceID(id *searchMessage.ResourceID) string {
})
}
// ask runs a query and returns the matched names; an engine error is the
// answer "error", so a query the engine rejects still shows in the matrix.
func ask(e search.Engine, request *search.IndexQuery) ([]string, error) {
resp, err := e.Search(context.Background(), request)
// query parses KQL the way the service does: what the parser rejects is a bad
// request before any engine sees it.
func query(kqlQuery string, ref *searchMessage.Reference, limit int32) (*search.IndexQuery, error) {
a, err := search.ParseQuery(kqlQuery)
if err != nil {
return nil, err
}
request := &search.IndexQuery{Query: a, Ref: ref}
if limit != 0 {
request.PageSize = conversions.ToPointer(limit)
}
return request, nil
}
func run(e search.Engine, kqlQuery string, ref *searchMessage.Reference, limit int32) (*search.IndexResult, error) {
request, err := query(kqlQuery, ref, limit)
if err != nil {
return nil, err
}
return e.Search(context.Background(), request)
}
// ask runs a query and returns the matched names; an error is the answer
// "error", so a query that is rejected still shows in the matrix.
func ask(e search.Engine, kqlQuery string, ref *searchMessage.Reference, limit int32) ([]string, error) {
resp, err := run(e, kqlQuery, ref, limit)
if err != nil {
return []string{"error"}, err
}
+4 -11
View File
@@ -1,7 +1,6 @@
package parity
import (
"context"
"fmt"
"strings"
@@ -11,7 +10,6 @@ import (
"github.com/opencloud-eu/reva/v3/pkg/errtypes"
"github.com/opencloud-eu/opencloud/pkg/conversions"
searchMessage "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/search/v0"
"github.com/opencloud-eu/opencloud/services/search/pkg/search"
)
@@ -288,16 +286,11 @@ var _ = Describe("Queries", func() {
Skip(e.unavailable)
}
request := &search.IndexQuery{Query: c.query, Ref: c.ref}
if c.limit != 0 {
request.PageSize = conversions.ToPointer(c.limit)
}
expected := override{want: c.want, wantCount: c.wantCount, wantBadRequest: c.wantBadRequest}
_, overridden := c.engineOverrides[name]
if c.wantBadRequest {
_, err := e.backend.Search(context.Background(), request)
_, err := run(e.backend, c.query, c.ref, c.limit)
answer := badRequestAnswer(err)
recordAnswer(row, name, answer)
if !overridden {
@@ -309,7 +302,7 @@ var _ = Describe("Queries", func() {
return
}
answer, err := ask(e.backend, request)
answer, err := ask(e.backend, c.query, c.ref, c.limit)
recordAnswer(row, name, answer)
if !overridden {
Expect(err).NotTo(HaveOccurred(), "the query has to answer, an empty result is an answer")
@@ -372,7 +365,7 @@ var _ = Describe("Operations", func() {
answers := make([][]string, len(c.expect))
errs := make([]error, len(c.expect))
for i, expect := range c.expect {
answers[i], errs[i] = ask(e.backend, &search.IndexQuery{Query: expect.query})
answers[i], errs[i] = ask(e.backend, expect.query, nil, 0)
recordAnswer(rows[i], name, answers[i])
}
@@ -449,7 +442,7 @@ var _ = Describe("Response", func() {
e.settle()
}
resp, err := e.backend.Search(context.Background(), &search.IndexQuery{Query: c.query})
resp, err := run(e.backend, c.query, nil, 0)
if err != nil {
recordAnswer(row, name, []string{"error"})
}
-38
View File
@@ -1,38 +0,0 @@
// Package bleve provides the ability to work with bleve queries.
package bleve
import (
bQuery "github.com/blevesearch/bleve/v2/search/query"
"github.com/opencloud-eu/opencloud/pkg/kql"
"github.com/opencloud-eu/opencloud/services/search/pkg/query"
)
// Creator is combines a Builder and a Compiler which is used to Create the query.
type Creator[T any] struct {
builder query.Builder
compiler query.Compiler[T]
}
// Create implements the Creator interface
func (c Creator[T]) Create(qs string) (T, error) {
var t T
builderAst, err := c.builder.Build(qs)
if err != nil {
return t, err
}
// shared KQL lowering pass: resolve field names + expand media-type aliases
// once, so the compiler below sees only canonical field:value nodes.
builderAst = query.Normalize(builderAst, query.ResolveField)
t, err = c.compiler.Compile(builderAst)
if err != nil {
return t, err
}
return t, nil
}
// DefaultCreator exposes a kql to bleve query creator.
var DefaultCreator = Creator[bQuery.Query]{kql.Builder{}, Compiler{}}
+1
View File
@@ -1,3 +1,4 @@
// Package query provides functions to work with the different search query flavours.
package query
import (
-19
View File
@@ -1,19 +0,0 @@
// Package query provides functions to work with the different search query flavours.
package query
import "github.com/opencloud-eu/opencloud/pkg/ast"
// Builder is the interface that wraps the basic Build method.
type Builder interface {
Build(qs string) (*ast.Ast, error)
}
// Compiler is the interface that wraps the basic Compile method.
type Compiler[T any] interface {
Compile(ast *ast.Ast) (T, error)
}
// Creator is the interface that wraps the basic Create method.
type Creator[T any] interface {
Create(qs string) (T, error)
}
@@ -9,7 +9,7 @@ import (
var _ = DescribeTable("PinnedRootID",
func(query, want string) {
Expect(search.PinnedRootID(query)).To(Equal(want))
Expect(search.PinnedRootID(parse(query))).To(Equal(want))
},
Entry("bare driveId is completed to the root id", `driveId:"1$2"`, "1$2!2"),
Entry("full root id passes through", `driveId:"1$2!4" name:x`, "1$2!4"),
@@ -24,7 +24,6 @@ var _ = DescribeTable("PinnedRootID",
Entry("a negated restriction disables pruning", `NOT driveId:"1$2" AND name:x`, ""),
Entry("restrictions inside groups do not pin", `(driveId:"1$2") AND name:x`, ""),
Entry("two different roots disable pruning", `driveId:"1$2" AND driveId:"1$3"`, ""),
Entry("invalid query, no pin", `((`, ""),
Entry("a wildcard drive id does not pin", `driveId:"1$*" AND name:x`, ""),
Entry("a wildcard space id does not pin", `driveId:"1$2*"`, ""),
)
+103
View File
@@ -0,0 +1,103 @@
package search
import (
"errors"
"strings"
"github.com/opencloud-eu/opencloud/pkg/ast"
"github.com/opencloud-eu/opencloud/pkg/kql"
)
// A scope narrows the whole search to one folder, so it cannot take part in a
// boolean expression and cannot be given twice.
var (
ErrNestedScope = errors.New("scope: must be a top-level restriction")
ErrRepeatedScope = errors.New("scope: must be given once")
ErrScopeOperator = errors.New("scope: cannot be negated or joined with OR")
)
// ExtractScope takes the scope restriction out of the query, together with
// the operator that joined it, and returns the remaining nodes and the scope.
func ExtractScope(nodes []ast.Node) ([]ast.Node, string, error) {
scopes := 0
for _, n := range nodes {
switch node := n.(type) {
case *ast.GroupNode:
if strings.EqualFold(node.Key, "scope") || hasKey(node.Nodes, "scope") {
return nil, "", ErrNestedScope
}
case *ast.StringNode:
if strings.EqualFold(node.Key, "scope") {
scopes++
}
}
}
if scopes > 1 {
return nil, "", ErrRepeatedScope
}
for i, n := range nodes {
node, ok := n.(*ast.StringNode)
if !ok || !strings.EqualFold(node.Key, "scope") {
continue
}
if i > 0 && (isOperator(nodes[i-1], kql.BoolNOT) || isOperator(nodes[i-1], kql.BoolOR)) {
return nil, "", ErrScopeOperator
}
if i+1 < len(nodes) && isOperator(nodes[i+1], kql.BoolOR) {
return nil, "", ErrScopeOperator
}
rest := append(append([]ast.Node{}, nodes[:i]...), nodes[i+1:]...)
switch {
case i < len(rest) && isBooleanOperator(rest[i]):
rest = append(rest[:i], rest[i+1:]...)
case i > 0 && isBooleanOperator(rest[i-1]):
rest = append(rest[:i-1], rest[i:]...)
}
return rest, strings.TrimSpace(node.Value), nil
}
return nodes, "", nil
}
// ExpandFavorites turns every is:favorite into the restriction on the user's
// favorites field, wherever it sits in the query.
func ExpandFavorites(nodes []ast.Node, userID string) {
for _, n := range nodes {
switch node := n.(type) {
case *ast.StringNode:
if strings.EqualFold(node.Key, "is") && strings.EqualFold(node.Value, "favorite") {
node.Key = "Favorites"
node.Value = userID
}
case *ast.GroupNode:
ExpandFavorites(node.Nodes, userID)
}
}
}
func hasKey(nodes []ast.Node, key string) bool {
for _, n := range nodes {
switch node := n.(type) {
case *ast.StringNode:
if strings.EqualFold(node.Key, key) {
return true
}
case *ast.GroupNode:
if strings.EqualFold(node.Key, key) || hasKey(node.Nodes, key) {
return true
}
}
}
return false
}
func isOperator(n ast.Node, value string) bool {
op, ok := n.(*ast.OperatorNode)
return ok && op.Value == value
}
func isBooleanOperator(n ast.Node) bool {
return isOperator(n, kql.BoolAND) || isOperator(n, kql.BoolOR)
}
+76
View File
@@ -0,0 +1,76 @@
package search_test
import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/opencloud-eu/opencloud/services/search/pkg/search"
)
var _ = DescribeTable("ExtractScope",
func(query, wantQuery, wantScope string) {
nodes, scope, err := search.ExtractScope(parse(query).Nodes)
Expect(err).ToNot(HaveOccurred())
Expect(scope).To(Equal(wantScope))
if wantQuery == "" {
Expect(nodes).To(BeEmpty())
return
}
Expect(render(nodes)).To(Equal(render(parse(wantQuery).Nodes)))
},
Entry("at the end", `name:"*file*" AND tag:foo AND scope:1$2!3`, `name:"*file*" AND tag:foo`, `1$2!3`),
Entry("at the start", `scope:1$2!3 AND name:x`, `name:x`, `1$2!3`),
Entry("in the middle", `name:x AND scope:1$2!3 AND tag:y`, `name:x AND tag:y`, `1$2!3`),
Entry("joined implicitly", `name:x scope:1$2!3`, `name:x`, `1$2!3`),
Entry("joined implicitly at the start", `scope:1$2!3 name:x`, `name:x`, `1$2!3`),
Entry("between free text", `foo scope:1$2!3 bar`, `foo bar`, `1$2!3`),
Entry("alone", `scope:1$2!3`, ``, `1$2!3`),
Entry("no scope", `name:x AND tag:y`, `name:x AND tag:y`, ``),
Entry("a quoted value is not a scope", `name:"scope:1$2!3"`, `name:"scope:1$2!3"`, ``),
)
var _ = DescribeTable("ExtractScope rejects a nested scope",
func(query string) {
_, _, err := search.ExtractScope(parse(query).Nodes)
Expect(err).To(MatchError(search.ErrNestedScope))
},
Entry("inside a group", `name:x AND (scope:1$2!3 OR tag:y)`),
Entry("inside a nested group", `name:x AND (tag:y OR (scope:1$2!3))`),
Entry("after a top-level scope", `scope:1$2!3 AND (scope:1$2!4)`),
Entry("as a group value", `name:x AND scope:(1$2!3)`),
Entry("as a group value inside a group", `name:x AND (tag:y OR scope:(1$2!3))`),
)
var _ = DescribeTable("ExtractScope rejects a scope that is negated or joined with OR",
func(query string) {
_, _, err := search.ExtractScope(parse(query).Nodes)
Expect(err).To(MatchError(search.ErrScopeOperator))
},
Entry("negated", `name:x AND NOT scope:1$2!3`),
Entry("negated at the start", `NOT scope:1$2!3 AND name:x`),
Entry("negated alone", `NOT scope:1$2!3`),
Entry("joined with OR", `name:x OR scope:1$2!3`),
Entry("joined with OR at the start", `scope:1$2!3 OR name:x`),
Entry("joined with OR in the middle", `name:x AND scope:1$2!3 OR tag:y`),
)
var _ = Describe("ExtractScope", func() {
It("rejects a second scope", func() {
_, _, err := search.ExtractScope(parse(`scope:1$2!3 AND name:x AND scope:1$2!4`).Nodes)
Expect(err).To(MatchError(search.ErrRepeatedScope))
})
})
var _ = DescribeTable("ExpandFavorites",
func(query, want string) {
a := parse(query)
search.ExpandFavorites(a.Nodes, "uid")
Expect(render(a.Nodes)).To(Equal(render(parse(want).Nodes)))
},
Entry("alone", `is:favorite`, `Favorites:uid`),
Entry("at the start", `is:favorite AND name:x`, `Favorites:uid AND name:x`),
Entry("in the middle", `name:x AND is:favorite AND tag:y`, `name:x AND Favorites:uid AND tag:y`),
Entry("negated", `NOT is:favorite`, `NOT Favorites:uid`),
Entry("inside a group", `name:x AND (is:favorite OR tag:y)`, `name:x AND (Favorites:uid OR tag:y)`),
Entry("a quoted value stays text", `name:"is:favorite"`, `name:"is:favorite"`),
)
+22 -26
View File
@@ -5,7 +5,6 @@ import (
"context"
"errors"
"fmt"
"regexp"
"strings"
"sync"
"time"
@@ -14,13 +13,13 @@ import (
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/opencloud-eu/reva/v3/pkg/conversions"
"github.com/opencloud-eu/reva/v3/pkg/errtypes"
"github.com/opencloud-eu/reva/v3/pkg/rgrpc/todo/pool"
"github.com/opencloud-eu/reva/v3/pkg/storage/utils/grants"
"github.com/opencloud-eu/reva/v3/pkg/utils"
"github.com/opencloud-eu/opencloud/pkg/ast"
"github.com/opencloud-eu/opencloud/pkg/kql"
"github.com/opencloud-eu/opencloud/pkg/log"
searchmsg "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/messages/search/v0"
searchsvc "github.com/opencloud-eu/opencloud/protogen/gen/opencloud/services/search/v0"
@@ -34,9 +33,6 @@ import (
// colliding with the old one. No migration; reindex to populate.
const SchemaVersion = 5
// the scope clause is removed together with the boolean operator that joins it to the rest of the query.
var scopeRegex = regexp.MustCompile(`(?:(?:AND|OR)\s+)?scope:\s*([^" "\n\r]*)(?:\s+(?:AND|OR)\b)?`)
// ErrResourceNotFound is returned when the index holds no document with the requested id
var ErrResourceNotFound = errors.New("resource not found")
@@ -47,9 +43,10 @@ var ErrOptimizeUnsupported = errors.New("the search engine merges its index on i
// ErrOptimizeInProgress is returned while another optimization of the index runs
var ErrOptimizeInProgress = errors.New("the index is being optimized already")
// IndexQuery is one search against the index.
// IndexQuery is one search against the index. The engine owns the query it
// is given and may rewrite it while compiling.
type IndexQuery struct {
Query string
Query *ast.Ast
Ref *searchmsg.Reference
PageSize *int32
Aggregations []*searchsvc.AggregationOption
@@ -319,18 +316,27 @@ func CompleteRootID(v string) string {
return v
}
// ParseQuery parses a KQL query; what the parser rejects is a bad request.
func ParseQuery(query string) (*ast.Ast, error) {
if strings.TrimSpace(query) == "" {
return nil, errtypes.BadRequest("empty query provided")
}
a, err := kql.Builder{}.Build(query)
if err != nil {
if kql.IsValidationError(err) {
return nil, errtypes.BadRequest(err.Error())
}
return nil, err
}
return a, nil
}
// PinnedRootID returns the single space root the query is pinned to via
// top-level AND driveId/RootID conjuncts, or "". OR, NOT and group-nested
// restrictions never pin: skipping a space would be wrong.
func PinnedRootID(query string) string {
a, err := kql.Builder{}.Build(query)
if err != nil {
return ""
}
return pinnedRootID(a)
}
func pinnedRootID(a *ast.Ast) string {
func PinnedRootID(a *ast.Ast) string {
pinned := ""
negated := false
for _, n := range a.Nodes {
@@ -370,13 +376,3 @@ func pinnedRootID(a *ast.Ast) string {
}
return pinned
}
// ParseScope extract a scope value from the query string and returns search, scope strings
func ParseScope(query string) (string, string) {
match := scopeRegex.FindStringSubmatch(query)
if len(match) >= 2 {
cut := match[0]
return strings.TrimSpace(strings.ReplaceAll(query, cut, "")), strings.TrimSpace(match[1])
}
return query, ""
}
+32 -45
View File
@@ -32,6 +32,7 @@ import (
"google.golang.org/grpc/metadata"
"google.golang.org/protobuf/types/known/fieldmaskpb"
"github.com/opencloud-eu/opencloud/pkg/ast"
"github.com/opencloud-eu/opencloud/pkg/conversions"
"github.com/opencloud-eu/opencloud/pkg/kql"
"github.com/opencloud-eu/opencloud/pkg/log"
@@ -88,7 +89,7 @@ type Service struct {
batchSize int
queryTemplate string
queryTemplate *QueryTemplate
}
var errSkipSpace error
@@ -110,9 +111,13 @@ var (
const unreachableStreakLimit = 5
// NewService creates a new Provider instance.
func NewService(gatewaySelector pool.Selectable[gateway.GatewayAPIClient], eng Engine, extractor content.Extractor, metrics *metrics.Metrics, logger log.Logger, cfg *config.Config) *Service {
func NewService(gatewaySelector pool.Selectable[gateway.GatewayAPIClient], eng Engine, extractor content.Extractor, metrics *metrics.Metrics, logger log.Logger, cfg *config.Config) (*Service, error) {
// NewBasicExtractor has no failure path
basic, _ := content.NewBasicExtractor(logger)
queryTemplate, err := ParseQueryTemplate(cfg.QueryTemplate)
if err != nil {
return nil, err
}
var s = &Service{
gatewaySelector: gatewaySelector,
@@ -127,30 +132,10 @@ func NewService(gatewaySelector pool.Selectable[gateway.GatewayAPIClient], eng E
batchSize: cfg.BatchSize,
queryTemplate: cfg.QueryTemplate,
queryTemplate: queryTemplate,
}
return s
}
// ExpandQueryTemplate fills {{.QUERY}} with the user query and the space-root placeholders per space.
func ExpandQueryTemplate(template, query string, space *provider.StorageSpace) string {
if template == "" {
return query
}
rootID := func(spaceType string) string {
if space.GetSpaceType() == spaceType {
return `"` + storagespace.FormatResourceID(space.GetRoot()) + `"`
}
return `"` + config.NoResourceID + `"`
}
return strings.NewReplacer(
config.QueryPlaceholder, query,
config.PersonalSpaceRootPlaceholder, rootID(_spaceTypePersonal),
config.ProjectSpaceRootPlaceholder, rootID(_spaceTypeProject),
).Replace(template)
return s, nil
}
// Search processes a search request and passes it down to the engine.
@@ -187,22 +172,19 @@ func (s *Service) Search(ctx context.Context, req *searchsvc.SearchRequest) (*se
}
currentUser := revactx.ContextMustGetUser(ctx)
// is:favorite expands in place to the user's favorites field, so it keeps its position and joining operator
query := strings.ReplaceAll(req.Query, "is:favorite", `Favorites:"`+currentUser.GetId().GetOpaqueId()+`"`)
// Extract scope from query if set
query, scope := ParseScope(query)
if query == "" {
return nil, errtypes.BadRequest("empty query provided")
}
queryAst, err := kql.Builder{}.Build(query)
queryAst, err := ParseQuery(req.Query)
if err != nil {
if kql.IsValidationError(err) {
return nil, errtypes.BadRequest(err.Error())
}
return nil, err
}
req.Query = query
ExpandFavorites(queryAst.Nodes, currentUser.GetId().GetOpaqueId())
nodes, scope, err := ExtractScope(queryAst.Nodes)
if err != nil {
return nil, errtypes.BadRequest(err.Error())
}
queryAst.Nodes = nodes
if len(queryAst.Nodes) == 0 {
return nil, errtypes.BadRequest("empty query provided")
}
var scopeRoot *provider.ResourceId
if len(scope) > 0 {
@@ -243,7 +225,7 @@ func (s *Service) Search(ctx context.Context, req *searchsvc.SearchRequest) (*se
// stays in the query, mountpoints are kept for path mapping
var pinnedRoot *provider.ResourceId
if req.Ref == nil {
if pinned := pinnedRootID(queryAst); pinned != "" {
if pinned := PinnedRootID(queryAst); pinned != "" {
if rid, err := storagespace.ParseID(pinned); err == nil {
pinnedRoot = &rid
}
@@ -326,7 +308,7 @@ func (s *Service) Search(ctx context.Context, req *searchsvc.SearchRequest) (*se
for i := 0; i < numWorkers; i++ {
errg.Go(func() error {
for space := range work {
res, err := s.searchIndex(ctx, req, space, mountpointMap[space.Id.OpaqueId], scopeRoot)
res, err := s.searchIndex(ctx, req, queryAst, space, mountpointMap[space.Id.OpaqueId], scopeRoot)
if err != nil && err != errSkipSpace {
return err
}
@@ -427,7 +409,7 @@ func engineFetchSize(from int32, pageSize *int32) int32 {
return math.MaxInt32
}
func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest, space *provider.StorageSpace, mountpointID string, scopeRoot *provider.ResourceId) (res *IndexResult, err error) {
func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest, query *ast.Ast, space *provider.StorageSpace, mountpointID string, scopeRoot *provider.ResourceId) (res *IndexResult, err error) {
// the workers run in an errgroup, which does not recover, one failing space must not affect the others
defer func() {
if r := recover(); r != nil {
@@ -531,14 +513,19 @@ func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest,
permissions = space.GetRootInfo().GetPermissionSet()
}
query := ExpandQueryTemplate(s.queryTemplate, req.Query, space)
expanded := s.queryTemplate.Expand(query, space)
if scopeRoot != nil {
// the path filter of the engines matches the scope folder as well
query = fmt.Sprintf(`(%s) AND NOT id:"%s"`, query, storagespace.FormatResourceID(scopeRoot))
expanded = &ast.Ast{Nodes: []ast.Node{
&ast.GroupNode{Nodes: expanded.Nodes},
&ast.OperatorNode{Value: kql.BoolAND},
&ast.OperatorNode{Value: kql.BoolNOT},
&ast.StringNode{Key: "id", Value: storagespace.FormatResourceID(scopeRoot), Exact: true},
}}
}
searchRequest := &IndexQuery{
Query: query,
Query: expanded,
Aggregations: req.GetAggregations(),
AggregationFilters: req.GetAggregationFilters(),
Ref: &searchmsg.Reference{
@@ -560,9 +547,9 @@ func (s *Service) searchIndex(ctx context.Context, req *searchsvc.SearchRequest,
return nil, err
}
if duration > _slowQueryDuration {
s.logger.Info().Interface("searchRequest", searchRequest).Str("duration", fmt.Sprint(duration)).Str("space", space.Id.OpaqueId).Int("hits", len(res.Matches)).Msg("slow space search")
s.logger.Info().Str("query", req.Query).Str("duration", fmt.Sprint(duration)).Str("space", space.Id.OpaqueId).Int("hits", len(res.Matches)).Msg("slow space search")
} else {
s.logger.Debug().Interface("searchRequest", searchRequest).Str("duration", fmt.Sprint(duration)).Str("space", space.Id.OpaqueId).Int("hits", len(res.Matches)).Msg("space search done")
s.logger.Debug().Str("query", req.Query).Str("duration", fmt.Sprint(duration)).Str("space", space.Id.OpaqueId).Int("hits", len(res.Matches)).Msg("space search done")
}
matches := make([]*searchmsg.Match, 0, len(res.Matches))
+19 -76
View File
@@ -98,7 +98,9 @@ var _ = Describe("Searchprovider", func() {
indexClient = &engineMocks.Engine{}
extractor = &contentMocks.Extractor{}
s = search.NewService(gatewaySelector, indexClient, extractor, nil, logger, &config.Config{})
var err error
s, err = search.NewService(gatewaySelector, indexClient, extractor, nil, logger, &config.Config{})
Expect(err).ToNot(HaveOccurred())
gatewayClient.On("Authenticate", mock.Anything, mock.Anything).Return(&gateway.AuthenticateResponse{
Status: status.NewOK(ctx),
@@ -118,7 +120,8 @@ var _ = Describe("Searchprovider", func() {
Describe("New", func() {
It("returns a new instance", func() {
s := search.NewService(gatewaySelector, indexClient, extractor, nil, logger, &config.Config{})
s, err := search.NewService(gatewaySelector, indexClient, extractor, nil, logger, &config.Config{})
Expect(err).ToNot(HaveOccurred())
Expect(s).ToNot(BeNil())
})
})
@@ -402,7 +405,9 @@ var _ = Describe("Searchprovider", func() {
}
return nil
}}
s = search.NewService(gatewaySelector, indexClient, probing, nil, logger, &config.Config{})
var err error
s, err = search.NewService(gatewaySelector, indexClient, probing, nil, logger, &config.Config{})
Expect(err).ToNot(HaveOccurred())
Expect(s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false)).To(MatchError(unreached))
Expect(attempts).To(Equal(map[string]int{"a.pdf": 1, "g.pdf": 1}))
@@ -427,7 +432,9 @@ var _ = Describe("Searchprovider", func() {
},
probe: func() error { return nil },
}
s = search.NewService(gatewaySelector, indexClient, probing, nil, logger, &config.Config{})
var err error
s, err = search.NewService(gatewaySelector, indexClient, probing, nil, logger, &config.Config{})
Expect(err).ToNot(HaveOccurred())
Expect(s.IndexSpace(&sprovider.StorageSpaceId{OpaqueId: "storageid$spaceid!spaceid"}, false)).To(MatchError(unreached))
Expect(attempts).To(HaveKeyWithValue("huge.pdf", 1))
@@ -668,19 +675,6 @@ var _ = Describe("Searchprovider", func() {
})
})
DescribeTable("ExpandQueryTemplate",
func(spaceType, expected string) {
space := &sprovider.StorageSpace{
SpaceType: spaceType,
Root: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "spaceid"},
}
Expect(search.ExpandQueryTemplate(`({{.QUERY}}) AND NOT id:{{.SPACE_ROOT_PERSONAL}} AND NOT id:{{.SPACE_ROOT_PROJECT}}`, "foo", space)).To(Equal(expected))
},
Entry("a personal space fills the personal placeholder", "personal", `(foo) AND NOT id:"storageid$spaceid!spaceid" AND NOT id:"none$none!none"`),
Entry("a project space fills the project placeholder", "project", `(foo) AND NOT id:"none$none!none" AND NOT id:"storageid$spaceid!spaceid"`),
Entry("a share fills neither", "grant", `(foo) AND NOT id:"none$none!none" AND NOT id:"none$none!none"`),
)
DescribeTable("SanitizeHighlights",
func(highlights, expected string) {
Expect(search.SanitizeHighlights(highlights)).To(Equal(expected))
@@ -833,18 +827,19 @@ var _ = Describe("Searchprovider", func() {
})
Expect(err).ToNot(HaveOccurred())
indexClient.AssertCalled(GinkgoT(), "Search", mock.Anything, mock.MatchedBy(func(req *search.IndexQuery) bool {
return req.Query == "Size:<10"
return render(req.Query.Nodes) == render(parse("Size:<10").Nodes)
}))
})
It("adds the query filter with the personal space root filled in", func() {
s := search.NewService(gatewaySelector, indexClient, extractor, nil, logger, &config.Config{
s, err := search.NewService(gatewaySelector, indexClient, extractor, nil, logger, &config.Config{
QueryTemplate: `({{.QUERY}}) AND (NOT path:"./.space" AND NOT id:{{.SPACE_ROOT_PERSONAL}})`,
})
_, err := s.Search(ctx, &searchsvc.SearchRequest{Query: "foo"})
Expect(err).ToNot(HaveOccurred())
_, err = s.Search(ctx, &searchsvc.SearchRequest{Query: "foo"})
Expect(err).ToNot(HaveOccurred())
indexClient.AssertCalled(GinkgoT(), "Search", mock.Anything, mock.MatchedBy(func(req *search.IndexQuery) bool {
return req.Query == `(foo) AND (NOT path:"./.space" AND NOT id:"storageid$personalspace!personalspace")`
return render(req.Query.Nodes) == render(parse(`(foo) AND (NOT path:"./.space" AND NOT id:"storageid$personalspace!personalspace")`).Nodes)
}))
})
@@ -853,7 +848,8 @@ var _ = Describe("Searchprovider", func() {
failingClient.On("Search", mock.Anything, mock.Anything).Run(func(mock.Arguments) {
panic("unexpected")
}).Return(nil, nil)
s := search.NewService(gatewaySelector, failingClient, extractor, nil, logger, &config.Config{})
s, err := search.NewService(gatewaySelector, failingClient, extractor, nil, logger, &config.Config{})
Expect(err).ToNot(HaveOccurred())
res, err := s.Search(ctx, &searchsvc.SearchRequest{Query: "foo"})
Expect(err).ToNot(HaveOccurred())
@@ -1113,7 +1109,7 @@ var _ = Describe("Searchprovider", func() {
Expect(match.Entity.Ref.Path).To(Equal("./path/to/Foo.pdf"))
indexClient.AssertCalled(GinkgoT(), "Search", mock.Anything, mock.MatchedBy(func(req *search.IndexQuery) bool {
return req.Query == `(foo) AND NOT id:"storageid$personalspace!scopefolder"`
return render(req.Query.Nodes) == render(parse(`(foo) AND NOT id:"storageid$personalspace!scopefolder"`).Nodes)
}))
})
})
@@ -1383,59 +1379,6 @@ var _ = Describe("Searchprovider", func() {
})
})
var _ = DescribeTable("Parse Scope",
func(pattern, wantSearch, wantScope string) {
gotSearch, gotScope := search.ParseScope(pattern)
Expect(gotSearch).To(Equal(wantSearch))
Expect(gotScope).To(Equal(wantScope))
},
Entry("When scope is at the end of the line",
`+Name:*file* +Tags:&quot;foo&quot; scope:<uuid>/folder/subfolder`,
`+Name:*file* +Tags:&quot;foo&quot;`,
`<uuid>/folder/subfolder`,
),
Entry("When scope is at the end of the line 2",
`+Name:*file* +Tags:&quot;foo&quot; scope:<uuid>/folder`,
`+Name:*file* +Tags:&quot;foo&quot;`,
`<uuid>/folder`,
),
Entry("When scope is at the end of the line 3",
`file scope:<uuid>/folder/subfolder`,
`file`,
`<uuid>/folder/subfolder`,
),
Entry("When scope is at the end of the line with a space",
`+Name:*file* +Tags:&quot;foo&quot; scope: <uuid>/folder/subfolder`,
`+Name:*file* +Tags:&quot;foo&quot;`,
`<uuid>/folder/subfolder`,
),
Entry("When scope is in the middle of the line",
`+Name:*file* scope:<uuid>/folder/subfolder +Tags:&quot;foo&quot;`,
`+Name:*file* +Tags:&quot;foo&quot;`,
`<uuid>/folder/subfolder`,
),
Entry("When scope is at the end of the line",
`scope:<uuid>/folder/subfolder +Name:*file*`,
`+Name:*file*`,
`<uuid>/folder/subfolder`,
),
Entry("When scope is at the begging of the line",
`scope:<uuid>/folder/subfolder file`,
`file`,
`<uuid>/folder/subfolder`,
),
Entry("When no scope",
`+Name:*file* +Tags:&quot;foo&quot;`,
`+Name:*file* +Tags:&quot;foo&quot;`,
``,
),
Entry("When scope is joined with AND, the operator goes with it",
`name:"*mediaTest*" AND mtime:last 30 days AND scope:1234$5678!90`,
`name:"*mediaTest*" AND mtime:last 30 days`,
`1234$5678!90`,
),
)
func ptr[T any](v T) *T {
return &v
}
+167
View File
@@ -0,0 +1,167 @@
package search
import (
"errors"
"fmt"
"strings"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/opencloud-eu/reva/v3/pkg/storagespace"
"github.com/opencloud-eu/opencloud/pkg/ast"
"github.com/opencloud-eu/opencloud/pkg/kql"
"github.com/opencloud-eu/opencloud/services/search/pkg/config"
)
// QueryTemplate is the parsed SEARCH_QUERY_TEMPLATE: a KQL tree with marker
// nodes where the user's query and the space roots go. An empty template
// expands to the bare query.
type QueryTemplate struct {
nodes []ast.Node
query *ast.GroupNode
queries int
stray bool
}
const (
queryMarker = "opencloudquerymarker"
personalRootMarker = "opencloudpersonalrootmarker"
projectRootMarker = "opencloudprojectrootmarker"
)
// ParseQueryTemplate parses the template once.
func ParseQueryTemplate(template string) (*QueryTemplate, error) {
if template == "" {
return &QueryTemplate{}, nil
}
source := strings.NewReplacer(
config.QueryPlaceholder, queryMarker,
config.PersonalSpaceRootPlaceholder, `"`+personalRootMarker+`"`,
config.ProjectSpaceRootPlaceholder, `"`+projectRootMarker+`"`,
).Replace(template)
if strings.Contains(source, "{{") || strings.Contains(source, "}}") {
return nil, errors.New("search query template: unknown placeholder")
}
parsed, err := kql.Builder{}.Build(source)
if err != nil {
return nil, fmt.Errorf("search query template: %w", err)
}
t := &QueryTemplate{nodes: parsed.Nodes}
t.findMarkers(parsed.Nodes)
switch {
case t.stray && t.queries == 0:
return nil, errors.New("search query template: " + config.QueryPlaceholder + " must be wrapped as (" + config.QueryPlaceholder + ")")
case t.queries != 1 || t.stray:
return nil, errors.New("search query template: must contain " + config.QueryPlaceholder + " exactly once")
}
return t, nil
}
func (t *QueryTemplate) findMarkers(nodes []ast.Node) {
for _, n := range nodes {
switch node := n.(type) {
case *ast.GroupNode:
if len(node.Nodes) == 1 {
if s, ok := node.Nodes[0].(*ast.StringNode); ok && s.Key == "" && s.Value == queryMarker {
t.query = node
t.queries++
continue
}
}
t.findMarkers(node.Nodes)
case *ast.StringNode:
if node.Value == queryMarker {
t.stray = true
}
}
}
}
// Expand builds the query the engine answers for one space: the template with
// the user's query and the space roots filled in. Every node is a copy, so the
// engine may rewrite the result and the inputs stay untouched.
func (t *QueryTemplate) Expand(query *ast.Ast, space *provider.StorageSpace) *ast.Ast {
if t.query == nil {
return &ast.Ast{Base: query.Base, Nodes: cloneNodes(query.Nodes, nil)}
}
rootID := func(spaceType string) string {
if space.GetSpaceType() == spaceType {
return storagespace.FormatResourceID(space.GetRoot())
}
return config.NoResourceID
}
// the user's nodes are copied without replace, so a marker in the user's
// query stays what it is
return &ast.Ast{Nodes: cloneNodes(t.nodes, func(n ast.Node) ast.Node {
if n == ast.Node(t.query) {
c := *t.query
c.Nodes = cloneNodes(query.Nodes, nil)
return &c
}
if s, ok := n.(*ast.StringNode); ok {
switch s.Value {
case personalRootMarker:
c := *s
c.Value = rootID(_spaceTypePersonal)
return &c
case projectRootMarker:
c := *s
c.Value = rootID(_spaceTypeProject)
return &c
}
}
return nil
})}
}
// cloneNodes deep-copies the nodes; replace may hand back a substitute for a
// node, which is taken as is.
func cloneNodes(nodes []ast.Node, replace func(ast.Node) ast.Node) []ast.Node {
out := make([]ast.Node, 0, len(nodes))
for _, n := range nodes {
if replace != nil {
if r := replace(n); r != nil {
out = append(out, r)
continue
}
}
switch node := n.(type) {
case *ast.StringNode:
c := *node
out = append(out, &c)
case *ast.BooleanNode:
c := *node
out = append(out, &c)
case *ast.DateTimeNode:
c := *node
c.Operator = cloneOperator(node.Operator)
out = append(out, &c)
case *ast.NumberNode:
c := *node
c.Operator = cloneOperator(node.Operator)
out = append(out, &c)
case *ast.OperatorNode:
out = append(out, cloneOperator(node))
case *ast.GroupNode:
c := *node
c.Nodes = cloneNodes(node.Nodes, replace)
out = append(out, &c)
default:
out = append(out, n)
}
}
return out
}
func cloneOperator(op *ast.OperatorNode) *ast.OperatorNode {
if op == nil {
return nil
}
c := *op
return &c
}
+144
View File
@@ -0,0 +1,144 @@
package search_test
import (
"fmt"
"strings"
"time"
sprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/opencloud-eu/opencloud/pkg/ast"
"github.com/opencloud-eu/opencloud/pkg/kql"
"github.com/opencloud-eu/opencloud/services/search/pkg/search"
)
func parse(query string) *ast.Ast {
GinkgoHelper()
a, err := kql.Builder{}.Build(query)
Expect(err).ToNot(HaveOccurred(), query)
return a
}
// render prints the tree without its source locations, so two parses of the
// same query compare equal
func render(nodes []ast.Node) string {
parts := make([]string, 0, len(nodes))
for _, n := range nodes {
switch node := n.(type) {
case *ast.StringNode:
parts = append(parts, node.Key+":"+node.Value)
case *ast.BooleanNode:
parts = append(parts, fmt.Sprintf("%s:%t", node.Key, node.Value))
case *ast.DateTimeNode:
parts = append(parts, node.Key+node.Operator.Value+node.Value.Format(time.RFC3339Nano))
case *ast.NumberNode:
parts = append(parts, fmt.Sprintf("%s%s%v", node.Key, node.Operator.Value, node.Value))
case *ast.OperatorNode:
parts = append(parts, node.Value)
case *ast.GroupNode:
parts = append(parts, node.Key+"("+render(node.Nodes)+")")
}
}
return strings.Join(parts, " ")
}
var _ = Describe("QueryTemplate", func() {
DescribeTable("ParseQueryTemplate",
func(template string, valid bool) {
_, err := search.ParseQueryTemplate(template)
if valid {
Expect(err).ToNot(HaveOccurred())
} else {
Expect(err).To(HaveOccurred())
}
},
Entry("empty", "", true),
Entry("bare query", `({{.QUERY}})`, true),
Entry("the default", `({{.QUERY}}) AND (NOT path:"./.space" AND NOT id:{{.SPACE_ROOT_PERSONAL}})`, true),
Entry("an OR", `({{.QUERY}}) OR mediatype:document`, true),
Entry("a parenthesis inside a value", `({{.QUERY}}) AND NOT name:"a(b"`, true),
Entry("query without parentheses", `{{.QUERY}}`, false),
Entry("query without parentheses in a conjunction", `{{.QUERY}} AND NOT mediatype:folder`, false),
Entry("query twice", `({{.QUERY}}) OR ({{.QUERY}})`, false),
Entry("query twice, once bare", `({{.QUERY}}) AND {{.QUERY}}`, false),
Entry("no query", `NOT mediatype:folder`, false),
Entry("unknown placeholder", `({{.QUERY}}) AND NOT id:{{.SPACE_ROOT_GRANT}}`, false),
Entry("broken placeholder", `({{.QUERY}}) AND NOT id:{{.SPACE_ROOT_PERSONAL}`, false),
Entry("unbalanced parentheses", `(({{.QUERY}})`, false),
Entry("dangling operators", `({{.QUERY}}) AND AND`, false),
Entry("trailing operator", `({{.QUERY}}) AND`, false),
)
DescribeTable("Expand fills the space roots",
func(spaceType, expected string) {
space := &sprovider.StorageSpace{
SpaceType: spaceType,
Root: &sprovider.ResourceId{StorageId: "storageid", SpaceId: "spaceid", OpaqueId: "spaceid"},
}
t, err := search.ParseQueryTemplate(`({{.QUERY}}) AND NOT id:{{.SPACE_ROOT_PERSONAL}} AND NOT id:{{.SPACE_ROOT_PROJECT}}`)
Expect(err).ToNot(HaveOccurred())
Expect(render(t.Expand(parse("foo"), space).Nodes)).To(Equal(render(parse(expected).Nodes)))
},
Entry("a personal space fills the personal placeholder", "personal", `(foo) AND NOT id:"storageid$spaceid!spaceid" AND NOT id:"none$none!none"`),
Entry("a project space fills the project placeholder", "project", `(foo) AND NOT id:"none$none!none" AND NOT id:"storageid$spaceid!spaceid"`),
Entry("a share fills neither", "grant", `(foo) AND NOT id:"none$none!none" AND NOT id:"none$none!none"`),
)
It("expands a nested query marker", func() {
t, err := search.ParseQueryTemplate(`(NOT mediatype:folder AND ({{.QUERY}})) OR tag:keep`)
Expect(err).ToNot(HaveOccurred())
expanded := t.Expand(parse(`name:x OR name:y`), &sprovider.StorageSpace{})
Expect(render(expanded.Nodes)).To(Equal(render(parse(`(NOT mediatype:folder AND (name:x OR name:y)) OR tag:keep`).Nodes)))
})
It("fills a root placeholder that is used twice", func() {
t, err := search.ParseQueryTemplate(`({{.QUERY}}) AND NOT id:{{.SPACE_ROOT_PERSONAL}} AND NOT parentid:{{.SPACE_ROOT_PERSONAL}}`)
Expect(err).ToNot(HaveOccurred())
space := &sprovider.StorageSpace{SpaceType: "personal", Root: &sprovider.ResourceId{StorageId: "1", SpaceId: "2", OpaqueId: "2"}}
expanded := t.Expand(parse(`name:x`), space)
Expect(render(expanded.Nodes)).To(Equal(render(parse(`(name:x) AND NOT id:"1$2!2" AND NOT parentid:"1$2!2"`).Nodes)))
})
It("leaves a marker in the user's query alone", func() {
t, err := search.ParseQueryTemplate(`({{.QUERY}}) AND NOT id:{{.SPACE_ROOT_PERSONAL}}`)
Expect(err).ToNot(HaveOccurred())
expanded := t.Expand(parse(`name:opencloudpersonalrootmarker`), &sprovider.StorageSpace{})
Expect(render(expanded.Nodes)).To(Equal(render(parse(`(name:opencloudpersonalrootmarker) AND NOT id:"none$none!none"`).Nodes)))
})
It("keeps the key of the query group", func() {
t, err := search.ParseQueryTemplate(`name:({{.QUERY}})`)
Expect(err).ToNot(HaveOccurred())
expanded := t.Expand(parse(`x OR y`), &sprovider.StorageSpace{})
Expect(render(expanded.Nodes)).To(Equal(render(parse(`name:(x OR y)`).Nodes)))
})
It("expands an empty template to the query itself", func() {
t, err := search.ParseQueryTemplate("")
Expect(err).ToNot(HaveOccurred())
query := parse(`name:x AND mtime>=2024-01-02T03:04:05Z AND size>1 AND hidden:true`)
Expect(render(t.Expand(query, &sprovider.StorageSpace{}).Nodes)).To(Equal(render(query.Nodes)))
})
It("hands out copies the engine may rewrite", func() {
t, err := search.ParseQueryTemplate(`({{.QUERY}}) AND NOT id:{{.SPACE_ROOT_PERSONAL}}`)
Expect(err).ToNot(HaveOccurred())
query := parse(`name:x`)
first := t.Expand(query, &sprovider.StorageSpace{})
first.Nodes[0].(*ast.GroupNode).Nodes[0].(*ast.StringNode).Value = "rewritten"
first.Nodes[3].(*ast.StringNode).Value = "rewritten"
second := t.Expand(query, &sprovider.StorageSpace{})
Expect(render(second.Nodes)).To(Equal(render(parse(`(name:x) AND NOT id:"none$none!none"`).Nodes)))
Expect(render(query.Nodes)).To(Equal("name:x"))
})
})