refactor(search): hand the engines the parsed query

The service parsed the query once for validation and every engine parsed the
expanded string again per space. Now the service parses once and the engines
compile an AST. The query template is parsed at startup and expanded by
substituting nodes, the indexer's up-to-date check is built as nodes as well.
This commit is contained in:
Dominik Schmidt committed 2026-11-27 17:27:16 +01:00
1 parent 97c4288be8
commit 11047abb6a
21 files changed
+412 -238

No files matched your search

+9 -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"
@@ -33,17 +32,17 @@ 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
compiler searchQuery.Compiler[query.Query]
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, compiler searchQuery.Compiler[query.Query], log log.Logger) *Backend {
return &Backend{
index: &serialIndex{bleveIndex: index},
queryCreator: queryCreator,
log: log,
index: &serialIndex{bleveIndex: index},
compiler: compiler,
log: log,
}
}
@@ -68,11 +67,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 := b.compiler.Compile(searchQuery.Normalize(sir.Query, searchQuery.ResolveField))
if err != nil {
if kql.IsValidationError(err) {
return nil, errtypes.BadRequest(err.Error())
}
return nil, err
}
+6 -3
View File
@@ -10,6 +10,7 @@ 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/content"
@@ -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, bleveQuery.Compiler{}, log.Logger{})
Expect(err).ToNot(HaveOccurred())
rootResource = search.Resource{
@@ -140,7 +141,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 +192,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, bleveQuery.Compiler{}, log.Logger{})
Expect(b).ToNot(BeNil())
})
})
+1 -1
View File
@@ -126,7 +126,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, bleveQuery.Compiler{}, log.NopLogger())
var wg sync.WaitGroup
for i := range 4 {
+2 -2
View File
@@ -34,7 +34,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, bleveQuery.Compiler{}, log.NopLogger()), idx
}
It("merges the segments of the index into one and keeps the documents", func() {
@@ -79,7 +79,7 @@ var _ = Describe("Optimize", func() {
Expect(err).ToNot(HaveOccurred())
DeferCleanup(idx.Close)
eng := bleve.NewBackend(idx, bleveQuery.DefaultCreator, log.NopLogger())
eng := bleve.NewBackend(idx, bleveQuery.Compiler{}, log.NopLogger())
Expect(eng.Optimize(context.Background())).To(MatchError(search.ErrOptimizeUnsupported))
})
})
+5 -2
View File
@@ -80,7 +80,7 @@ func Server(cfg *config.Config) *cobra.Command {
}
}()
eng = bleve.NewBackend(idx, bleveQuery.DefaultCreator, logger)
eng = bleve.NewBackend(idx, bleveQuery.Compiler{}, logger)
case "open-search":
client, err := opensearch.NewClient(cfg.Engine.OpenSearch.Client)
if err != nil {
@@ -122,7 +122,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)
}
+10 -3
View File
@@ -15,6 +15,7 @@ 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/opensearch"
@@ -151,7 +152,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 +218,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) {
+37 -5
View File
@@ -10,9 +10,12 @@ import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/types"
"github.com/opencloud-eu/reva/v3/pkg/errtypes"
"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/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/internal/opensearchtest"
@@ -81,7 +84,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, bleveQuery.Compiler{}, log.Logger{})
load(backend, fixtures)
return testEngine{name: "bleve", backend: backend, settle: func() {}}
@@ -167,10 +170,39 @@ 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 := kql.Builder{}.Build(kqlQuery)
if err != nil {
if kql.IsValidationError(err) {
return nil, errtypes.BadRequest(err.Error())
}
return nil, err
}
request := &search.IndexQuery{Query: a, Ref: ref}
if limit != 0 {
request.PageSize = conversions.ToPointer(limit)
}
return request, nil
}
// run runs a query against an engine.
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{}}
-10
View File
@@ -3,17 +3,7 @@ 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*"`, ""),
)
+4 -13
View File
@@ -19,8 +19,6 @@ import (
"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"
@@ -47,9 +45,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
@@ -322,15 +321,7 @@ func CompleteRootID(v string) string {
// 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 {
+22 -32
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.
@@ -243,7 +228,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 +311,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 +412,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 +516,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 +550,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 -23
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)
}))
})
})
+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.
type QueryTemplate struct {
nodes []ast.Node
query *ast.GroupNode
personal *ast.StringNode
project *ast.StringNode
}
const (
queryMarker = "opencloudquerymarker"
personalRootMarker = "opencloudpersonalrootmarker"
projectRootMarker = "opencloudprojectrootmarker"
)
// ParseQueryTemplate parses the template once. An empty template is allowed
// and expands to the bare query.
func ParseQueryTemplate(template string) (*QueryTemplate, error) {
if template == "" {
return nil, nil
}
if strings.Count(template, config.QueryPlaceholder) != 1 {
return nil, errors.New("search query template: must contain " + config.QueryPlaceholder + " exactly once")
}
wrapped := "(" + config.QueryPlaceholder + ")"
if !strings.Contains(template, wrapped) {
return nil, errors.New("search query template: " + config.QueryPlaceholder + " must be wrapped as " + wrapped)
}
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)
if t.query == nil {
return nil, errors.New("search query template: " + config.QueryPlaceholder + " must be wrapped as " + wrapped)
}
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
continue
}
}
t.findMarkers(node.Nodes)
case *ast.StringNode:
switch node.Value {
case personalRootMarker:
t.personal = node
case projectRootMarker:
t.project = node
}
}
}
}
// 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 == 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
}
return &ast.Ast{Nodes: cloneNodes(t.nodes, func(n ast.Node) ast.Node {
switch n {
case t.query:
return &ast.GroupNode{Base: t.query.Base, Nodes: cloneNodes(query.Nodes, nil)}
case t.personal:
c := *t.personal
c.Value = rootID(_spaceTypePersonal)
return &c
case t.project:
c := *t.project
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
}
+118
View File
@@ -0,0 +1,118 @@
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("expands an empty template to the query itself", func() {
var t *search.QueryTemplate
query := parse(`name:x AND mtime>=2024-01-02T03:04:05Z`)
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"))
})
})