Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[pkg/ottl] Change grammar to support expressing statements context via path names #34875

Merged
27 changes: 27 additions & 0 deletions .chloggen/ottl_statements_context_change_grammar.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: enhancement
edmocosta marked this conversation as resolved.
Show resolved Hide resolved

# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
component: pkg/ottl

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: "Change the OTTL grammar to support expressing statements context via path names"

# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
issues: [29017]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext:
edmocosta marked this conversation as resolved.
Show resolved Hide resolved

# If your change doesn't affect end users or the exported elements of any package,
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: [api]
5 changes: 5 additions & 0 deletions pkg/ottl/contexts/internal/path.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
var _ ottl.Path[any] = &TestPath[any]{}

type TestPath[K any] struct {
C string
N string
KeySlice []ottl.Key[K]
NextPath *TestPath[K]
Expand All @@ -21,6 +22,10 @@ func (p *TestPath[K]) Name() string {
return p.N
}

func (p *TestPath[K]) Context() string {
return p.C
}

func (p *TestPath[K]) Next() ottl.Path[K] {
if p.NextPath == nil {
return nil
Expand Down
2 changes: 1 addition & 1 deletion pkg/ottl/expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -741,7 +741,7 @@ func (p *Parser[K]) newGetter(val value) (Getter[K], error) {
return &literal[K]{value: *i}, nil
}
if eL.Path != nil {
np, err := newPath[K](eL.Path.Fields)
np, err := p.newPath(eL.Path)
if err != nil {
return nil, err
}
Expand Down
78 changes: 71 additions & 7 deletions pkg/ottl/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,15 @@ type Enum int64

type EnumSymbol string

func buildOriginalText(fields []field) string {
func buildOriginalText(path *path) string {
var builder strings.Builder
for i, f := range fields {
if path.Context != "" {
builder.WriteString(path.Context)
if len(path.Fields) > 0 {
builder.WriteString(".")
}
}
for i, f := range path.Fields {
builder.WriteString(f.Name)
if len(f.Keys) > 0 {
for _, k := range f.Keys {
Expand All @@ -38,21 +44,28 @@ func buildOriginalText(fields []field) string {
builder.WriteString("]")
}
}
if i != len(fields)-1 {
if i != len(path.Fields)-1 {
builder.WriteString(".")
}
}
return builder.String()
}

func newPath[K any](fields []field) (*basePath[K], error) {
if len(fields) == 0 {
func (p *Parser[K]) newPath(path *path) (*basePath[K], error) {
if len(path.Fields) == 0 {
return nil, fmt.Errorf("cannot make a path from zero fields")
}
originalText := buildOriginalText(fields)

pathContext, fields, err := p.parsePathContext(path)
if err != nil {
return nil, err
}

originalText := buildOriginalText(path)
var current *basePath[K]
for i := len(fields) - 1; i >= 0; i-- {
current = &basePath[K]{
context: pathContext,
name: fields[i].Name,
keys: newKeys[K](fields[i].Keys),
nextPath: current,
Expand All @@ -64,10 +77,56 @@ func newPath[K any](fields []field) (*basePath[K], error) {
return current, nil
}

func (p *Parser[K]) parsePathContext(path *path) (string, []field, error) {
fields := path.Fields
var pathContext string
if path.Context != "" {
// nil or empty pathContextNames means the Parser isn't handling the grammar path's
// context yet, so it falls back to the previous behavior with the path.Context value
// as the first path's segment.
if p.pathContextNames == nil || len(p.pathContextNames) == 0 {
fields = append([]field{{Name: path.Context}}, fields...)
} else if _, ok := p.pathContextNames[path.Context]; !ok {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can remove this else.

if p.validatePathContextNames {
return "", nil, fmt.Errorf(`context "%s" from path "%s" is not valid, it must be replaced by one of: %s`, path.Context, buildOriginalText(path), p.buildPathContextNamesText(""))
}
fields = append([]field{{Name: path.Context}}, fields...)
} else {
pathContext = path.Context
}
} else if p.validatePathContextNames {
originalText := buildOriginalText(path)
return "", nil, fmt.Errorf(`missing context name for path "%s", valid options are: %s`, originalText, p.buildPathContextNamesText(originalText))
}

return pathContext, fields, nil
}

func (p *Parser[K]) buildPathContextNamesText(path string) string {
var builder strings.Builder
var suffix string
if path != "" {
suffix = "." + path
}

i := 0
for ctx := range p.pathContextNames {
builder.WriteString(fmt.Sprintf(`"%s%s"`, ctx, suffix))
if i != len(p.pathContextNames)-1 {
builder.WriteString(", ")
}
i++
}
return builder.String()
}

// Path represents a chain of path parts in an OTTL statement, such as `body.string`.
// A Path has a name, and potentially a set of keys.
// If the path in the OTTL statement contains multiple parts (separated by a dot (`.`)), then the Path will have a pointer to the next Path.
type Path[K any] interface {
// Context is the OTTL context name of this Path.
Context() string

// Name is the name of this segment of the path.
Name() string

Expand All @@ -86,6 +145,7 @@ type Path[K any] interface {
var _ Path[any] = &basePath[any]{}

type basePath[K any] struct {
context string
name string
keys []Key[K]
nextPath *basePath[K]
Expand All @@ -94,6 +154,10 @@ type basePath[K any] struct {
originalText string
}

func (p *basePath[K]) Context() string {
return p.context
}

func (p *basePath[K]) Name() string {
return p.name
}
Expand Down Expand Up @@ -412,7 +476,7 @@ func (p *Parser[K]) buildArg(argVal value, argType reflect.Type) (any, error) {
if argVal.Literal == nil || argVal.Literal.Path == nil {
return nil, fmt.Errorf("must be a path")
}
np, err := newPath[K](argVal.Literal.Path.Fields)
np, err := p.newPath(argVal.Literal.Path)
if err != nil {
return nil, err
}
Expand Down
139 changes: 138 additions & 1 deletion pkg/ottl/functions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2230,6 +2230,14 @@ func Test_basePath_Name(t *testing.T) {
assert.Equal(t, "test", n)
}

func Test_basePath_Context(t *testing.T) {
bp := basePath[any]{
context: "log",
}
n := bp.Context()
assert.Equal(t, "log", n)
}

func Test_basePath_Next(t *testing.T) {
bp := basePath[any]{
nextPath: &basePath[any]{},
Expand Down Expand Up @@ -2352,6 +2360,13 @@ func Test_basePath_NextWithIsComplete(t *testing.T) {
}

func Test_newPath(t *testing.T) {
ps, _ := NewParser[any](
defaultFunctionsForTests(),
testParsePath[any],
componenttest.NewNopTelemetrySettings(),
WithEnumParser[any](testParseEnum),
)

fields := []field{
{
Name: "body",
Expand All @@ -2365,7 +2380,8 @@ func Test_newPath(t *testing.T) {
},
},
}
np, err := newPath[any](fields)

np, err := ps.newPath(&path{Fields: fields})
assert.NoError(t, err)
p := Path[any](np)
assert.Equal(t, "body", p.Name())
Expand All @@ -2384,6 +2400,127 @@ func Test_newPath(t *testing.T) {
assert.Nil(t, i)
}

func Test_newPath_WithPathContextNames(t *testing.T) {
tests := []struct {
name string
pathContext string
pathContextNames []string
validationEnabled bool
contextParsedAsField bool
expectedError bool
}{
{
name: "with no context",
pathContextNames: []string{"log"},
},
{
name: "with context",
pathContext: "log",
pathContextNames: []string{"log"},
},
{
name: "with multiple contexts",
pathContext: "span",
pathContextNames: []string{"log", "span"},
},
{
name: "with invalid context and validation disabled",
pathContext: "span",
pathContextNames: []string{"log"},
validationEnabled: false,
contextParsedAsField: true,
},
{
name: "with invalid context and validation enabled",
pathContext: "span",
pathContextNames: []string{"log"},
validationEnabled: true,
expectedError: true,
},
{
name: "with valid context and validation enabled",
pathContext: "spanevent",
pathContextNames: []string{"spanevent"},
validationEnabled: true,
},
{
name: "with no context and validation enabled",
pathContextNames: []string{"spanevent"},
validationEnabled: true,
expectedError: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ps, _ := NewParser[any](
defaultFunctionsForTests(),
testParsePath[any],
componenttest.NewNopTelemetrySettings(),
WithEnumParser[any](testParseEnum),
WithPathContextNames[any](tt.pathContextNames),
WithPathContextNameValidation[any](tt.validationEnabled),
)

gp := &path{
Context: tt.pathContext,
Fields: []field{
{
Name: "body",
},
{
Name: "string",
Keys: []key{
{
String: ottltest.Strp("key"),
},
},
},
}}

np, err := ps.newPath(gp)
if tt.expectedError {
assert.Error(t, err)
return
}
assert.NoError(t, err)
p := Path[any](np)
if tt.contextParsedAsField {
assert.Equal(t, tt.pathContext, p.Name())
assert.Equal(t, "", p.Context())
assert.Nil(t, p.Keys())
p = p.Next()
}
var bodyStringFuncValue string
if tt.pathContext != "" {
bodyStringFuncValue = fmt.Sprintf("%s.body.string[key]", tt.pathContext)
} else {
bodyStringFuncValue = "body.string[key]"
}
assert.Equal(t, "body", p.Name())
assert.Nil(t, p.Keys())
assert.Equal(t, bodyStringFuncValue, p.String())
if !tt.contextParsedAsField {
assert.Equal(t, tt.pathContext, p.Context())
}
p = p.Next()
assert.Equal(t, "string", p.Name())
assert.Equal(t, bodyStringFuncValue, p.String())
if !tt.contextParsedAsField {
assert.Equal(t, tt.pathContext, p.Context())
}
assert.Nil(t, p.Next())
assert.Equal(t, 1, len(p.Keys()))
v, err := p.Keys()[0].String(context.Background(), struct{}{})
assert.NoError(t, err)
assert.Equal(t, "key", *v)
i, err := p.Keys()[0].Int(context.Background(), struct{}{})
assert.NoError(t, err)
assert.Nil(t, i)
})
}
}

func Test_baseKey_String(t *testing.T) {
bp := baseKey[any]{
s: ottltest.Strp("test"),
Expand Down
3 changes: 2 additions & 1 deletion pkg/ottl/grammar.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,8 @@ func (v *value) checkForCustomError() error {

// path represents a telemetry path mathExpression.
type path struct {
Fields []field `parser:"@@ ( '.' @@ )*"`
Context string `parser:"(@Lowercase '.')?"`
Fields []field `parser:"@@ ( '.' @@ )*"`
}

// field is an item within a path.
Expand Down
Loading
Loading