refactor(search): take scope and is:favorite out of the tree instead of the text

This commit is contained in:
Dominik Schmidt committed 2026-11-27 17:27:25 +01:00
1 parent 11047abb6a
commit b3becdd35f
5 files changed
+147 -77

No files matched your search

+85
View File
@@ -0,0 +1,85 @@
package search
import (
"errors"
"strings"
"github.com/opencloud-eu/opencloud/pkg/ast"
"github.com/opencloud-eu/opencloud/pkg/kql"
)
// ErrNestedScope is returned when the scope sits inside a group: it narrows
// the whole search to a folder and cannot take part in a boolean expression.
var ErrNestedScope = errors.New("scope: must be a top-level restriction")
// 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) {
for i, n := range nodes {
node, ok := n.(*ast.StringNode)
if !ok {
if group, isGroup := n.(*ast.GroupNode); isGroup && hasKey(group.Nodes, "scope") {
return nil, "", ErrNestedScope
}
continue
}
if !strings.EqualFold(node.Key, "scope") {
continue
}
rest := append(append([]ast.Node{}, nodes[:i]...), nodes[i+1:]...)
if i > 0 && isOperator(rest[i-1], kql.BoolNOT) {
rest = append(rest[:i-1], rest[i:]...)
i--
}
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 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)
}
+52
View File
@@ -0,0 +1,52 @@
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 with OR", `name:x OR scope:1$2!3`, `name:x`, `1$2!3`),
Entry("negated", `name:x AND NOT scope:1$2!3`, `name:x`, `1$2!3`),
Entry("negated at the start", `NOT scope:1$2!3 AND name:x`, `name:x`, `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 _ = Describe("ExtractScope", func() {
It("rejects a scope inside a group", func() {
_, _, err := search.ExtractScope(parse(`name:x AND (scope:1$2!3 OR tag:y)`).Nodes)
Expect(err).To(MatchError(search.ErrNestedScope))
})
})
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"`),
)
-14
View File
@@ -5,7 +5,6 @@ import (
"context"
"errors"
"fmt"
"regexp"
"strings"
"sync"
"time"
@@ -32,9 +31,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")
@@ -361,13 +357,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, ""
}
+10 -10
View File
@@ -172,22 +172,22 @@ 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 := kql.Builder{}.Build(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 {
@@ -1379,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
}