Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .chloggen/add-when-function.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

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

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Add the `When` OTTL converter for selecting a value based on a lambda condition.

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

# (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:

# 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: []
19 changes: 19 additions & 0 deletions pkg/ottl/e2e/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1627,6 +1627,7 @@ func Test_e2e_converters(t *testing.T) {
}

func Test_e2e_ottl_features(t *testing.T) {
ottltest.SetFeatureGateForTest(t, metadata.OttlFunctionsEnableLambdaFeatureGate, true)
Comment thread
edmocosta marked this conversation as resolved.
Outdated
tests := []struct {
name string
statement string
Expand Down Expand Up @@ -1888,6 +1889,24 @@ func Test_e2e_ottl_features(t *testing.T) {
tCtx.GetLogRecord().Attributes().PutStr("test", "pass")
},
},
{
statement: `set(attributes["test"], When(() => attributes["int_value"] > 0, "positive", "negative"))`,
want: func(tCtx *ottllog.TransformContext) {
tCtx.GetLogRecord().Attributes().PutStr("test", "negative")
},
},
{
statement: `set(attributes["test"], When(() => IsMap(attributes["foo"]), attributes["foo"]["bar"], "fail"))`,
want: func(tCtx *ottllog.TransformContext) {
tCtx.GetLogRecord().Attributes().PutStr("test", "pass")
},
},
{
statement: `set(attributes["test"], When(() => IsMap(attributes["foo"]), When(() => attributes["foo"]["bar"] == "pass", "pass", "fail"), "fail"))`,
want: func(tCtx *ottllog.TransformContext) {
tCtx.GetLogRecord().Attributes().PutStr("test", "pass")
},
},
}

for _, tt := range tests {
Expand Down
30 changes: 30 additions & 0 deletions pkg/ottl/ottlfuncs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,7 @@ Available Converters:
- [UUIDv7](#UUIDv7)
- [Values](#values)
- [Weekday](#weekday)
- [When](#when)
- [XXH3](#xxh3)
- [XXH128](#xxh128)
- [Year](#year)
Expand Down Expand Up @@ -2806,6 +2807,35 @@ Examples:

- `Weekday(Now())`

### When

> [!IMPORTANT]
> This function is alpha and may change in future releases. It requires the [`ottl.functions.enableLambda`](../documentation.md#feature-gates) feature gate to be enabled.

`When(condition, trueValue, falseValue)`

The `When` converter returns `trueValue` when `condition` evaluates to true, otherwise it returns `falseValue`.

`condition` is a lambda expression with no parameters that returns a `boolean`.

`trueValue` and `falseValue` are OTTL expressions or literal values.

If `condition` does not return a `boolean`, it returns an error.

Examples:

Select a value based on a type check:

- `When(() => IsMap(log.attributes), "map", "not map")`

Select a value based on a comparison:

- `When(() => attributes["int_value"] > 0, "positive", "negative")`

Store the result:

- `set(log.attributes["result"], When(() => IsMap(log.attributes), "yes", "no"))`

### XXH3

`XXH3(value)`
Expand Down
67 changes: 67 additions & 0 deletions pkg/ottl/ottlfuncs/func_when.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package ottlfuncs // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/ottlfuncs"

import (
"context"
"errors"

"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/ottlfuncs/internal/funcutil"
)

type WhenArguments[K any] struct {
Condition ottl.LambdaExpression[K]
TrueValue ottl.Getter[K]
FalseValue ottl.Getter[K]
}

func NewWhenFactory[K any]() ottl.Factory[K] {
return ottl.NewFactory("When", &WhenArguments[K]{}, createWhenFunction[K])
}

func createWhenFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ottl.ExprFunc[K], error) {
args, ok := oArgs.(*WhenArguments[K])
if !ok {
return nil, errors.New("WhenFactory args must be of type *WhenArguments[K]")
}
return whenFunction(&args.Condition, args.TrueValue, args.FalseValue), nil
}

func whenFunction[K any](condition *ottl.LambdaExpression[K], trueValueGetter, falseValueGetter ottl.Getter[K]) ottl.ExprFunc[K] {
var trueValue any
var falseValue any
if tv, ok := ottl.GetLiteralValue(trueValueGetter); ok {
trueValue = tv
}
if fv, ok := ottl.GetLiteralValue(falseValueGetter); ok {
falseValue = fv
}

return func(ctx context.Context, tCtx K) (any, error) {
lb, err := condition.Activate(ctx, 0)
if err != nil {
return nil, err
}
defer lb.Close()

match, err := funcutil.EvaluateLambdaActivation[K, bool](tCtx, lb)
if err != nil {
return nil, err
}

if match {
if trueValue != nil {
return trueValue, nil
}
return trueValueGetter.Get(ctx, tCtx)
}

if falseValue != nil {
return falseValue, nil
}

return falseValueGetter.Get(ctx, tCtx)
}
}
151 changes: 151 additions & 0 deletions pkg/ottl/ottlfuncs/func_when_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package ottlfuncs

import (
"context"
"errors"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
)

func Test_when(t *testing.T) {
asLiteralGetter := func(v any) ottl.Getter[any] {
getter, err := ottl.NewTestingLiteralGetter[any](true, ottl.StandardGetSetter[any]{
Getter: func(context.Context, any) (any, error) {
return v, nil
},
})
require.NoError(t, err)
return getter
}

tests := []struct {
name string
condition *ottl.LambdaExpression[any]
trueValue ottl.Getter[any]
falseValue ottl.Getter[any]
want any
}{
{
name: "condition true with literal values",
condition: ottl.NewTestingLambdaExpression[any]([]string{}, func(_ context.Context, _ any, _ func(string) any) (any, error) {
return true, nil
}),
trueValue: asLiteralGetter("true"),
falseValue: asLiteralGetter("false"),
want: "true",
},
{
name: "condition false with literal values",
condition: ottl.NewTestingLambdaExpression[any]([]string{}, func(_ context.Context, _ any, _ func(string) any) (any, error) {
return false, nil
}),
trueValue: asLiteralGetter("true"),
falseValue: asLiteralGetter("false"),
want: "false",
},
{
name: "condition true with dynamic values",
condition: ottl.NewTestingLambdaExpression[any]([]string{}, func(_ context.Context, _ any, _ func(string) any) (any, error) {
return true, nil
}),
trueValue: &ottl.StandardGetSetter[any]{Getter: func(context.Context, any) (any, error) {
return int64(1), nil
}},
falseValue: &ottl.StandardGetSetter[any]{Getter: func(context.Context, any) (any, error) {
return int64(0), nil
}},
want: int64(1),
},
{
name: "condition false with dynamic values",
condition: ottl.NewTestingLambdaExpression[any]([]string{}, func(_ context.Context, _ any, _ func(string) any) (any, error) {
return false, nil
}),
trueValue: &ottl.StandardGetSetter[any]{Getter: func(context.Context, any) (any, error) {
return int64(1), nil
}},
falseValue: &ottl.StandardGetSetter[any]{Getter: func(context.Context, any) (any, error) {
return int64(0), nil
}},
want: int64(0),
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
exprFunc := whenFunction(tt.condition, tt.trueValue, tt.falseValue)
got, err := exprFunc(t.Context(), nil)
require.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}

func Test_when_unused_branch(t *testing.T) {
condition := ottl.NewTestingLambdaExpression[any]([]string{}, func(_ context.Context, _ any, _ func(string) any) (any, error) {
return true, nil
})
trueValue := &ottl.StandardGetSetter[any]{Getter: func(context.Context, any) (any, error) {
return "true", nil
}}
falseValue := &ottl.StandardGetSetter[any]{Getter: func(context.Context, any) (any, error) {
return nil, errors.New("should not be reached")
}}

exprFunc := whenFunction(condition, trueValue, falseValue)
got, err := exprFunc(t.Context(), nil)
require.NoError(t, err)
assert.Equal(t, "true", got)
}

func Test_when_lambda_type_error(t *testing.T) {
condition := ottl.NewTestingLambdaExpression[any]([]string{}, func(_ context.Context, _ any, _ func(string) any) (any, error) {
return "not a bool", nil
})
trueValue := &ottl.StandardGetSetter[any]{Getter: func(context.Context, any) (any, error) {
return "true", nil
}}
falseValue := &ottl.StandardGetSetter[any]{Getter: func(context.Context, any) (any, error) {
return "false", nil
}}

exprFunc := whenFunction(condition, trueValue, falseValue)
_, err := exprFunc(t.Context(), nil)
require.Error(t, err)
assert.ErrorContains(t, err, "lambda expression must return a value of type bool")
}

func Test_createWhenFunction(t *testing.T) {
fCtx := ottl.FunctionContext{}
condition := ottl.NewTestingLambdaExpression[any]([]string{}, func(_ context.Context, _ any, _ func(string) any) (any, error) {
return true, nil
})
trueValue := &ottl.StandardGetSetter[any]{Getter: func(context.Context, any) (any, error) {
return "true", nil
}}
falseValue := &ottl.StandardGetSetter[any]{Getter: func(context.Context, any) (any, error) {
return "false", nil
}}

t.Run("valid args", func(t *testing.T) {
fn, err := createWhenFunction[any](fCtx, &WhenArguments[any]{
Condition: *condition,
TrueValue: trueValue,
FalseValue: falseValue,
})
require.NoError(t, err)
require.NotNil(t, fn)
})

t.Run("invalid args type", func(t *testing.T) {
_, err := createWhenFunction[any](fCtx, &struct{}{})
assert.EqualError(t, err, "WhenFactory args must be of type *WhenArguments[K]")
})
}
1 change: 1 addition & 0 deletions pkg/ottl/ottlfuncs/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ func converters[K any]() []ottl.Factory[K] {
NewURLFactory[K](),
NewValuesFactory[K](),
NewWeekdayFactory[K](),
NewWhenFactory[K](),
NewUserAgentFactory[K](),
NewAppendFactory[K](),
NewDeleteIndexFactory[K](),
Expand Down
Loading