Skip to content

Commit c00c4db

Browse files
edmocostaf7o
authored andcommitted
[pkg/ottl] Change grammar to support expressing statements context via path names (open-telemetry#34875)
**Description:** <Describe what has changed.> <!--Ex. Fixing a bug - Describe the bug and how this fixes the issue. Ex. Adding a feature - Explain what this achieves.--> This PR is part of the open-telemetry#29017, and introduces the necessary OTTL Grammar/Parser changes to make it possible for statements express their context via path names. This first iteration changes the grammar to parse the first `path` segment as the `Context` name, for example, the path `foo.bar.field` would be parsed as the following AST example: `{Context: "foo", Fields: [{Name: "bar"}, {Name: "field"}]}`, instead of `{Fields: [{Name: "foo"},{Name: "bar"}, {Name: "field"}]}`. To make it non-breaking to all components during the transition time and development, this PR also changes the `ottl.Parser[k].newPath` function to, by default, fall this new behavior back to the previous one, using the grammar's parsed `Context` value as the first path segment (`Fields[0]`). Two new `Parser[K]` options were added, `WithPathContextNames` and `WithPathContextNameValidation`, The first option will be used to enable the statements context support, parsing the first path segment as Context when the value maches any configured context names, or falling it back otherwise. The second option will be used to enable the validation and turning off the backward compatible mode, raising an error when paths have no context prefix, or when it's invalid. For more details, please check the open-telemetry#29017 discussion out. **Link to tracking Issue:** open-telemetry#29017 **Testing:** - Unit tests **Documentation:** - No documentation changes were made at this point.
1 parent e780a88 commit c00c4db

File tree

8 files changed

+286
-31
lines changed

8 files changed

+286
-31
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Use this changelog template to create an entry for release notes.
2+
3+
# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
4+
change_type: breaking
5+
6+
# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
7+
component: pkg/ottl
8+
9+
# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
10+
note: "Change the OTTL grammar to support expressing statements context via path names"
11+
12+
# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
13+
issues: [29017]
14+
15+
# (Optional) One or more lines of additional information to render under the primary note.
16+
# These lines will be padded with 2 spaces and then inserted directly into the document.
17+
# Use pipe (|) for multiline entries.
18+
subtext: "The `ottl.Path` interface requires a new method: `Context() string`"
19+
20+
# If your change doesn't affect end users or the exported elements of any package,
21+
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
22+
# Optional: The change log or logs in which this entry should be included.
23+
# e.g. '[user]' or '[user, api]'
24+
# Include 'user' if the change is relevant to end users.
25+
# Include 'api' if there is a change to a library API.
26+
# Default: '[user]'
27+
change_logs: [api]

pkg/ottl/contexts/internal/path.go

+5
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
var _ ottl.Path[any] = &TestPath[any]{}
1313

1414
type TestPath[K any] struct {
15+
C string
1516
N string
1617
KeySlice []ottl.Key[K]
1718
NextPath *TestPath[K]
@@ -21,6 +22,10 @@ func (p *TestPath[K]) Name() string {
2122
return p.N
2223
}
2324

25+
func (p *TestPath[K]) Context() string {
26+
return p.C
27+
}
28+
2429
func (p *TestPath[K]) Next() ottl.Path[K] {
2530
if p.NextPath == nil {
2631
return nil

pkg/ottl/expression.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -741,7 +741,7 @@ func (p *Parser[K]) newGetter(val value) (Getter[K], error) {
741741
return &literal[K]{value: *i}, nil
742742
}
743743
if eL.Path != nil {
744-
np, err := newPath[K](eL.Path.Fields)
744+
np, err := p.newPath(eL.Path)
745745
if err != nil {
746746
return nil, err
747747
}

pkg/ottl/functions.go

+71-7
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,15 @@ type Enum int64
2222

2323
type EnumSymbol string
2424

25-
func buildOriginalText(fields []field) string {
25+
func buildOriginalText(path *path) string {
2626
var builder strings.Builder
27-
for i, f := range fields {
27+
if path.Context != "" {
28+
builder.WriteString(path.Context)
29+
if len(path.Fields) > 0 {
30+
builder.WriteString(".")
31+
}
32+
}
33+
for i, f := range path.Fields {
2834
builder.WriteString(f.Name)
2935
if len(f.Keys) > 0 {
3036
for _, k := range f.Keys {
@@ -38,21 +44,28 @@ func buildOriginalText(fields []field) string {
3844
builder.WriteString("]")
3945
}
4046
}
41-
if i != len(fields)-1 {
47+
if i != len(path.Fields)-1 {
4248
builder.WriteString(".")
4349
}
4450
}
4551
return builder.String()
4652
}
4753

48-
func newPath[K any](fields []field) (*basePath[K], error) {
49-
if len(fields) == 0 {
54+
func (p *Parser[K]) newPath(path *path) (*basePath[K], error) {
55+
if len(path.Fields) == 0 {
5056
return nil, fmt.Errorf("cannot make a path from zero fields")
5157
}
52-
originalText := buildOriginalText(fields)
58+
59+
pathContext, fields, err := p.parsePathContext(path)
60+
if err != nil {
61+
return nil, err
62+
}
63+
64+
originalText := buildOriginalText(path)
5365
var current *basePath[K]
5466
for i := len(fields) - 1; i >= 0; i-- {
5567
current = &basePath[K]{
68+
context: pathContext,
5669
name: fields[i].Name,
5770
keys: newKeys[K](fields[i].Keys),
5871
nextPath: current,
@@ -64,10 +77,56 @@ func newPath[K any](fields []field) (*basePath[K], error) {
6477
return current, nil
6578
}
6679

80+
func (p *Parser[K]) parsePathContext(path *path) (string, []field, error) {
81+
hasPathContextNames := len(p.pathContextNames) > 0
82+
if path.Context != "" {
83+
// no pathContextNames means the Parser isn't handling the grammar path's context yet,
84+
// so it falls back to the previous behavior with the path.Context value as the first
85+
// path's segment.
86+
if !hasPathContextNames {
87+
return "", append([]field{{Name: path.Context}}, path.Fields...), nil
88+
}
89+
90+
if _, ok := p.pathContextNames[path.Context]; !ok {
91+
return "", path.Fields, fmt.Errorf(`context "%s" from path "%s" is not valid, it must be replaced by one of: %s`, path.Context, buildOriginalText(path), p.buildPathContextNamesText(""))
92+
}
93+
94+
return path.Context, path.Fields, nil
95+
}
96+
97+
if hasPathContextNames {
98+
originalText := buildOriginalText(path)
99+
return "", nil, fmt.Errorf(`missing context name for path "%s", possibly valid options are: %s`, originalText, p.buildPathContextNamesText(originalText))
100+
}
101+
102+
return "", path.Fields, nil
103+
}
104+
105+
func (p *Parser[K]) buildPathContextNamesText(path string) string {
106+
var builder strings.Builder
107+
var suffix string
108+
if path != "" {
109+
suffix = "." + path
110+
}
111+
112+
i := 0
113+
for ctx := range p.pathContextNames {
114+
builder.WriteString(fmt.Sprintf(`"%s%s"`, ctx, suffix))
115+
if i != len(p.pathContextNames)-1 {
116+
builder.WriteString(", ")
117+
}
118+
i++
119+
}
120+
return builder.String()
121+
}
122+
67123
// Path represents a chain of path parts in an OTTL statement, such as `body.string`.
68124
// A Path has a name, and potentially a set of keys.
69125
// 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.
70126
type Path[K any] interface {
127+
// Context is the OTTL context name of this Path.
128+
Context() string
129+
71130
// Name is the name of this segment of the path.
72131
Name() string
73132

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

88147
type basePath[K any] struct {
148+
context string
89149
name string
90150
keys []Key[K]
91151
nextPath *basePath[K]
@@ -94,6 +154,10 @@ type basePath[K any] struct {
94154
originalText string
95155
}
96156

157+
func (p *basePath[K]) Context() string {
158+
return p.context
159+
}
160+
97161
func (p *basePath[K]) Name() string {
98162
return p.name
99163
}
@@ -412,7 +476,7 @@ func (p *Parser[K]) buildArg(argVal value, argType reflect.Type) (any, error) {
412476
if argVal.Literal == nil || argVal.Literal.Path == nil {
413477
return nil, fmt.Errorf("must be a path")
414478
}
415-
np, err := newPath[K](argVal.Literal.Path.Fields)
479+
np, err := p.newPath(argVal.Literal.Path)
416480
if err != nil {
417481
return nil, err
418482
}

pkg/ottl/functions_test.go

+120-1
Original file line numberDiff line numberDiff line change
@@ -2230,6 +2230,14 @@ func Test_basePath_Name(t *testing.T) {
22302230
assert.Equal(t, "test", n)
22312231
}
22322232

2233+
func Test_basePath_Context(t *testing.T) {
2234+
bp := basePath[any]{
2235+
context: "log",
2236+
}
2237+
n := bp.Context()
2238+
assert.Equal(t, "log", n)
2239+
}
2240+
22332241
func Test_basePath_Next(t *testing.T) {
22342242
bp := basePath[any]{
22352243
nextPath: &basePath[any]{},
@@ -2352,6 +2360,13 @@ func Test_basePath_NextWithIsComplete(t *testing.T) {
23522360
}
23532361

23542362
func Test_newPath(t *testing.T) {
2363+
ps, _ := NewParser[any](
2364+
defaultFunctionsForTests(),
2365+
testParsePath[any],
2366+
componenttest.NewNopTelemetrySettings(),
2367+
WithEnumParser[any](testParseEnum),
2368+
)
2369+
23552370
fields := []field{
23562371
{
23572372
Name: "body",
@@ -2365,7 +2380,8 @@ func Test_newPath(t *testing.T) {
23652380
},
23662381
},
23672382
}
2368-
np, err := newPath[any](fields)
2383+
2384+
np, err := ps.newPath(&path{Fields: fields})
23692385
assert.NoError(t, err)
23702386
p := Path[any](np)
23712387
assert.Equal(t, "body", p.Name())
@@ -2384,6 +2400,109 @@ func Test_newPath(t *testing.T) {
23842400
assert.Nil(t, i)
23852401
}
23862402

2403+
func Test_newPath_WithPathContextNames(t *testing.T) {
2404+
tests := []struct {
2405+
name string
2406+
pathContext string
2407+
pathContextNames []string
2408+
expectedError string
2409+
}{
2410+
{
2411+
name: "with no path context",
2412+
pathContextNames: []string{"log"},
2413+
expectedError: `missing context name for path "body.string[key]", valid options are: "log.body.string[key]"`,
2414+
},
2415+
{
2416+
name: "with no path context and configuration",
2417+
},
2418+
{
2419+
name: "with valid path context",
2420+
pathContext: "log",
2421+
pathContextNames: []string{"log"},
2422+
},
2423+
{
2424+
name: "with invalid path context",
2425+
pathContext: "span",
2426+
pathContextNames: []string{"log"},
2427+
expectedError: `context "span" from path "span.body.string[key]" is not valid, it must be replaced by one of: "log"`,
2428+
},
2429+
{
2430+
name: "with multiple configured contexts",
2431+
pathContext: "span",
2432+
pathContextNames: []string{"log", "span"},
2433+
},
2434+
}
2435+
2436+
for _, tt := range tests {
2437+
t.Run(tt.name, func(t *testing.T) {
2438+
ps, _ := NewParser[any](
2439+
defaultFunctionsForTests(),
2440+
testParsePath[any],
2441+
componenttest.NewNopTelemetrySettings(),
2442+
WithEnumParser[any](testParseEnum),
2443+
WithPathContextNames[any](tt.pathContextNames),
2444+
)
2445+
2446+
gp := &path{
2447+
Context: tt.pathContext,
2448+
Fields: []field{
2449+
{
2450+
Name: "body",
2451+
},
2452+
{
2453+
Name: "string",
2454+
Keys: []key{
2455+
{
2456+
String: ottltest.Strp("key"),
2457+
},
2458+
},
2459+
},
2460+
}}
2461+
2462+
np, err := ps.newPath(gp)
2463+
if tt.expectedError != "" {
2464+
assert.Error(t, err, tt.expectedError)
2465+
return
2466+
}
2467+
assert.NoError(t, err)
2468+
p := Path[any](np)
2469+
contextParsedAsField := len(tt.pathContextNames) == 0 && tt.pathContext != ""
2470+
if contextParsedAsField {
2471+
assert.Equal(t, tt.pathContext, p.Name())
2472+
assert.Equal(t, "", p.Context())
2473+
assert.Nil(t, p.Keys())
2474+
p = p.Next()
2475+
}
2476+
var bodyStringFuncValue string
2477+
if tt.pathContext != "" {
2478+
bodyStringFuncValue = fmt.Sprintf("%s.body.string[key]", tt.pathContext)
2479+
} else {
2480+
bodyStringFuncValue = "body.string[key]"
2481+
}
2482+
assert.Equal(t, "body", p.Name())
2483+
assert.Nil(t, p.Keys())
2484+
assert.Equal(t, bodyStringFuncValue, p.String())
2485+
if !contextParsedAsField {
2486+
assert.Equal(t, tt.pathContext, p.Context())
2487+
}
2488+
p = p.Next()
2489+
assert.Equal(t, "string", p.Name())
2490+
assert.Equal(t, bodyStringFuncValue, p.String())
2491+
if !contextParsedAsField {
2492+
assert.Equal(t, tt.pathContext, p.Context())
2493+
}
2494+
assert.Nil(t, p.Next())
2495+
assert.Len(t, p.Keys(), 1)
2496+
v, err := p.Keys()[0].String(context.Background(), struct{}{})
2497+
assert.NoError(t, err)
2498+
assert.Equal(t, "key", *v)
2499+
i, err := p.Keys()[0].Int(context.Background(), struct{}{})
2500+
assert.NoError(t, err)
2501+
assert.Nil(t, i)
2502+
})
2503+
}
2504+
}
2505+
23872506
func Test_baseKey_String(t *testing.T) {
23882507
bp := baseKey[any]{
23892508
s: ottltest.Strp("test"),

pkg/ottl/grammar.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,8 @@ func (v *value) checkForCustomError() error {
253253

254254
// path represents a telemetry path mathExpression.
255255
type path struct {
256-
Fields []field `parser:"@@ ( '.' @@ )*"`
256+
Context string `parser:"(@Lowercase '.')?"`
257+
Fields []field `parser:"@@ ( '.' @@ )*"`
257258
}
258259

259260
// field is an item within a path.

pkg/ottl/parser.go

+17
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ type Parser[K any] struct {
5858
pathParser PathExpressionParser[K]
5959
enumParser EnumParser
6060
telemetrySettings component.TelemetrySettings
61+
pathContextNames map[string]struct{}
6162
}
6263

6364
func NewParser[K any](
@@ -91,6 +92,22 @@ func WithEnumParser[K any](parser EnumParser) Option[K] {
9192
}
9293
}
9394

95+
// WithPathContextNames sets the context names to be considered when parsing a Path value.
96+
// When this option is empty or nil, all Path segments are considered fields, and the
97+
// Path.Context value is always empty.
98+
// When this option is configured, and the path's context is empty or is not present in
99+
// this context names list, it results into an error.
100+
func WithPathContextNames[K any](contexts []string) Option[K] {
101+
return func(p *Parser[K]) {
102+
pathContextNames := make(map[string]struct{}, len(contexts))
103+
for _, ctx := range contexts {
104+
pathContextNames[ctx] = struct{}{}
105+
}
106+
107+
p.pathContextNames = pathContextNames
108+
}
109+
}
110+
94111
// ParseStatements parses string statements into ottl.Statement objects ready for execution.
95112
// Returns a slice of statements and a nil error on successful parsing.
96113
// If parsing fails, returns nil and a joined error containing each error per failed statement.

0 commit comments

Comments
 (0)